{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 2.线程篇\n",
    "\n",
    "在线预览：<https://github.lesschina.com/python/base/concurrency/3.并发编程-线程篇.html>\n",
    "\n",
    "示例代码：<a href=\"https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Thread\" target=\"_blank\">https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Thread</a>\n",
    "\n",
    "终于说道线程了，心酸啊，进程还有点东西下次接着聊，这周4天外出，所以注定发文少了`+_+`\n",
    "\n",
    "用过Java或者Net的重点都在线程这块，Python的重点其实在上篇，但线程自有其独到之处～比如资源共享（更轻量级）\n",
    "\n",
    "这次采用循序渐进的方式讲解，`先使用，再深入，然后扩展，最后来个案例`，呃.呃.呃.先这样计划～欢迎纠正错误\n",
    "\n",
    "## 2.1.入门篇\n",
    "\n",
    "官方文档：<a href=\"https://docs.python.org/3/library/threading.html\" target=\"_blank\">https://docs.python.org/3/library/threading.html</a>\n",
    "\n",
    "进程是由若干线程组成的（一个进程至少有一个线程）\n",
    "\n",
    "### 2.1.1.线程案例\n",
    "\n",
    "用法和`Process`差不多，咱先看个案例：`Thread(target=test, args=(i, ))`\n",
    "```py\n",
    "import os\n",
    "from threading import Thread, current_thread \n",
    "\n",
    "def test(name):\n",
    "    # current_thread()返回当前线程的实例\n",
    "    thread_name = current_thread().name  # 获取线程名\n",
    "    print(f\"[编号：{name}]，ThreadName：{thread_name}\\nPID：{os.getpid()}，PPID：{os.getppid()}\")\n",
    "\n",
    "def main():\n",
    "    t_list = [Thread(target=test, args=(i, )) for i in range(5)]\n",
    "    for t in t_list:\n",
    "        t.start() # 批量启动\n",
    "    for t in t_list:\n",
    "        t.join() # 批量回收\n",
    "\n",
    "    # 主线程\n",
    "    print(f\"[Main]ThreadName：{current_thread().name}\\nPID：{os.getpid()}，PPID：{os.getppid()}\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（同一个进程ID）\n",
    "```\n",
    "[编号：0]，ThreadName：Thread-1\n",
    "PID：20533，PPID：19830\n",
    "[编号：1]，ThreadName：Thread-2\n",
    "PID：20533，PPID：19830\n",
    "[编号：2]，ThreadName：Thread-3\n",
    "PID：20533，PPID：19830\n",
    "[编号：3]，ThreadName：Thread-4\n",
    "PID：20533，PPID：19830\n",
    "[编号：4]，ThreadName：Thread-5\n",
    "PID：20533，PPID：19830\n",
    "[Main]ThreadName：MainThread\n",
    "PID：22636，PPID：19830\n",
    "```\n",
    "注意一点：Python里面的线程是**<a href=\"https://baike.baidu.com/item/POSIX线程\" target=\"_blank\">Posix Thread</a>**\n",
    "\n",
    "### 2.1.2.指定线程名\n",
    "\n",
    "如果想给线程设置一个Div的名字呢？：\n",
    "```py\n",
    "from threading import Thread, current_thread\n",
    "\n",
    "def test():\n",
    "    # current_thread()返回当前线程的实例\n",
    "    print(f\"ThreadName：{current_thread().name}\")\n",
    "\n",
    "def main():\n",
    "    t1 = Thread(target=test, name=\"小明\")\n",
    "    t2 = Thread(target=test)\n",
    "    t1.start()\n",
    "    t2.start()\n",
    "    t1.join()\n",
    "    t2.join()\n",
    "\n",
    "    # 主线程\n",
    "    print(f\"[Main]，ThreadName：{current_thread().name}\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（你指定有特点的名字，没指定就使用默认命令【联想古时候奴隶名字都是编号，主人赐名就有名了】）\n",
    "```\n",
    "ThreadName：小明\n",
    "ThreadName：Thread-1\n",
    "[Main]，ThreadName：MainThread\n",
    "```\n",
    "\n",
    "类的方式创建线程\n",
    "```py\n",
    "from threading import Thread\n",
    "\n",
    "class MyThread(Thread):\n",
    "    def __init__(self, name):\n",
    "        # 设个坑，你可以自行研究下\n",
    "        super().__init__()  # 放在后面就报错了\n",
    "        self.name = name\n",
    "\n",
    "    def run(self):\n",
    "        print(self.name)\n",
    "\n",
    "def main():\n",
    "    t = MyThread(name=\"小明\")\n",
    "    t.start()\n",
    "    t.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（和Thread初始化的name冲突了【变量名得注意哦】）\n",
    "```\n",
    "小明\n",
    "```\n",
    "\n",
    "### 2.1.3.线程池案例\n",
    "\n",
    "```py\n",
    "from multiprocessing.dummy import Pool as ThreadPool, current_process\n",
    "\n",
    "def test(i):\n",
    "    # 本质调用了：threading.current_thread\n",
    "    print(f\"[编号{i}]{current_process().name}\")\n",
    "\n",
    "def main():\n",
    "    p = ThreadPool()\n",
    "    for i in range(5):\n",
    "        p.apply_async(test, args=(i, ))\n",
    "    p.close()\n",
    "    p.join()\n",
    "\n",
    "    print(f\"{current_process().name}\")\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "[编号0]Thread-3\n",
    "[编号1]Thread-4\n",
    "[编号3]Thread-2\n",
    "[编号2]Thread-1\n",
    "[编号4]Thread-3\n",
    "MainThread\n",
    "```\n",
    "\n",
    "#### 微微扩展一下\n",
    "\n",
    "对上面代码，项目里面一般都会这么优化：（并行这块线程后面会讲，不急）\n",
    "```py\n",
    "from multiprocessing.dummy import Pool as ThreadPool, current_process\n",
    "\n",
    "def test(i):\n",
    "    # 源码：current_process = threading.current_thread\n",
    "    print(f\"[编号{i}]{current_process().name}\")\n",
    "\n",
    "def main():\n",
    "    p = ThreadPool()\n",
    "    p.map_async(test, range(5))\n",
    "    p.close()\n",
    "    p.join()\n",
    "\n",
    "    print(f\"{current_process().name}\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "[编号0]Thread-2\n",
    "[编号1]Thread-4\n",
    "[编号2]Thread-3\n",
    "[编号4]Thread-2\n",
    "[编号3]Thread-1\n",
    "MainThread\n",
    "```\n",
    "代码改动很小（循环换成了map）性能提升很明显（密集型操作）\n",
    "\n",
    "### 2.1.4.其他扩展\n",
    "\n",
    "Thread初始化参数：\n",
    "1. daemon：是否为后台线程（主线程退出后，后台线程就退出了）\n",
    "\n",
    "Thread实例对象的方法:\n",
    "1. isAlive(): 返回线程是否活动的\n",
    "2. getName(): 返回线程名\n",
    "3. setName(): 设置线程名\n",
    "4. isDaemon():是否为后台线程\n",
    "5. setDaemon(True):设置后台线程\n",
    "\n",
    "threading模块提供的一些方法：\n",
    "1. threading.currentThread(): 返回当前的线程实例\n",
    "2. threading.enumerate(): 返回一个包含正在运行的线程List(线程启动后、结束前)\n",
    "3. threading.activeCount(): 返回正在运行的线程数量，与len(threading.enumerate())有相同的结果\n",
    "\n",
    "看一个小案例：\n",
    "```py\n",
    "import time\n",
    "from threading import Thread, active_count\n",
    "\n",
    "def test1():\n",
    "    print(\"test1\")\n",
    "    time.sleep(1)\n",
    "    print(\"test1 ok\")\n",
    "\n",
    "def test2():\n",
    "    print(\"test2\")\n",
    "    time.sleep(2)\n",
    "    print(\"test2 ok\")\n",
    "\n",
    "def main():\n",
    "    t1 = Thread(target=test1)\n",
    "    t2 = Thread(target=test2, daemon=True)\n",
    "    t1.start()\n",
    "    t2.start()\n",
    "    t1.join()\n",
    "    print(active_count())\n",
    "    print(t1.is_alive)\n",
    "    print(t2.is_alive)\n",
    "    # 除非加这一句才等daemon线程，不然主线程退出的时候后台线程就退出了\n",
    "    # t2.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "下次就以`multiprocessing.dummy`模块为例了，API和`threading`几乎一样，进行了一些并发的封装，性价比更高"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.2.加强篇\n",
    "\n",
    "其实以前的`Linux中`是没有线程这个概念的，`Windows`程序员经常使用线程，这一看～方便啊，然后可能是当时程序员偷懒了，就把进程模块改了改（这就是为什么之前说Linux下的多进程编程其实没有Win下那么“重量级”），弄了个精简版进程==>`线程`（内核是分不出`进程和线程`的，反正`PCB`个数都是一样）\n",
    "\n",
    "多线程和多进程最大的不同在于，多进程中，同一个变量，各自有一份拷贝存在于每个进程中，互不影响，而多线程中，所有变量都由所有线程共享（**全局变量和堆 ==> 线程间共享。进程的栈 ==> 线程平分而独占**）\n",
    "\n",
    "还记得通过`current_thread()`获取的线程信息吗？难道线程也没个id啥的？一起看看：（**通过`ps -Lf pid 来查看LWP`**）\n",
    "\n",
    "![1.线程ID.png](https://images2018.cnblogs.com/blog/1127869/201808/1127869-20180824103431457-1550038732.png)\n",
    "\n",
    "回顾：进程共享的内容：（回顾：<a href=\"http://www.cnblogs.com/dotnetcrazy/p/9363810.html\" target=\"_blank\">http://www.cnblogs.com/dotnetcrazy/p/9363810.html</a>）\n",
    "1. 代码（.text）\n",
    "2. 文件描述符（fd）\n",
    "3. 内存映射（mmap）\n",
    "\n",
    "### 2.2.1.线程同步~互斥锁Lock\n",
    "\n",
    "线程之间共享数据的确方便，但是也容易出现数据混乱的现象，来看个例子：\n",
    "```py\n",
    "from multiprocessing.dummy import threading\n",
    "\n",
    "num = 0  # def global num\n",
    "\n",
    "def test(i):\n",
    "    print(f\"子进程：{i}\")\n",
    "    global num\n",
    "    for i in range(100000):\n",
    "        num += 1\n",
    "\n",
    "def main():\n",
    "    p_list = [threading.Thread(target=test, args=(i, )) for i in range(5)]\n",
    "    for i in p_list:\n",
    "        i.start()\n",
    "    for i in p_list:\n",
    "        i.join()\n",
    "    print(num)  # 应该是500000，发生了数据混乱，结果少了很多\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（应该是`500000`，发生了数据混乱，只剩下`358615`）\n",
    "```\n",
    "子进程：0\n",
    "子进程：1\n",
    "子进程：2\n",
    "子进程：3\n",
    "子进程：4\n",
    "452238\n",
    "```\n",
    "\n",
    "#### Lock案例\n",
    "\n",
    "**`共享资源+CPU调度==>数据混乱==解决==>线程同步`** 这时候`Lock`就该上场了\n",
    "\n",
    "**互斥锁是实现线程同步最简单的一种方式**，读写都加锁（读写都会串行）\n",
    "\n",
    "先看看上面例子怎么解决调：\n",
    "```py\n",
    "from multiprocessing.dummy import threading, Lock\n",
    "\n",
    "num = 0  # def global num\n",
    "\n",
    "def test(i, lock):\n",
    "    print(f\"子进程：{i}\")\n",
    "    global num\n",
    "    for i in range(100000):\n",
    "        with lock:\n",
    "            num += 1\n",
    "\n",
    "def main():\n",
    "    lock = Lock()\n",
    "    p_list = [threading.Thread(target=test, args=(i, lock)) for i in range(5)]\n",
    "    for i in p_list:\n",
    "        i.start()\n",
    "    for i in p_list:\n",
    "        i.join()\n",
    "    print(num)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：`time python3 1.thread.2.py`\n",
    "```\n",
    "子进程：0\n",
    "子进程：1\n",
    "子进程：2\n",
    "子进程：3\n",
    "子进程：4\n",
    "500000\n",
    "\n",
    "real\t0m2.846s\n",
    "user\t0m1.897s\n",
    "sys\t0m3.159s\n",
    "```\n",
    "\n",
    "#### 优化下\n",
    "\n",
    "lock设置为全局或者局部，性能几乎一样。循环换成map后性能有所提升（<a href=\"https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Thread/2.lock_queue\" target=\"_blank\">测试案例在Code中</a>）\n",
    "\n",
    "```py\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Lock\n",
    "\n",
    "num = 0  # def global num\n",
    "lock = Lock()\n",
    "\n",
    "def test(i):\n",
    "    print(f\"子进程：{i}\")\n",
    "    global num\n",
    "    global lock\n",
    "    for i in range(100000):\n",
    "        with lock:\n",
    "            num += 1\n",
    "\n",
    "def main():\n",
    "    p = ThreadPool()\n",
    "    p.map_async(test, list(range(5)))\n",
    "    p.close()\n",
    "    p.join()\n",
    "\n",
    "    print(num)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "\n",
    "`time python3 1.thread.2.py`\n",
    "```\n",
    "子进程：0\n",
    "子进程：1\n",
    "子进程：3\n",
    "子进程：2\n",
    "子进程：4\n",
    "500000\n",
    "\n",
    "real\t0m2.468s\n",
    "user\t0m1.667s\n",
    "sys\t0m2.644s\n",
    "```\n",
    "本来多线程访问共享资源的时候可以并行，加锁后就部分串行了（没获取到的线程就阻塞等了）\n",
    "\n",
    "【**项目中可以多次加锁，每次加锁只对修改部分加(尽量少的代码)** 】（**以后会说协程和Actor模型**）\n",
    "\n",
    "补充：以前都是这么写的，现在支持`with`托管了（有时候还会用到，所以了解下）：【net是直接`lock大括号包起来`】\n",
    "```py\n",
    "#### 以前写法：\n",
    "lock.acquire() # 获取锁\n",
    "try:\n",
    "    num += 1\n",
    "finally:\n",
    "    lock.release() # 释放锁\n",
    "\n",
    "#### 等价简写\n",
    "with lock:\n",
    "    num += 1\n",
    "```\n",
    "扩展知识:（GIL在扩展篇会详说）\n",
    "1. GIL的作用：多线程情况下必须存在资源的竞争，GIL是为了保证在解释器级别的线程唯一使用共享资源（cpu）。\n",
    "2. 同步锁的作用：为了保证解释器级别下的自己编写的程序唯一使用共享资源产生了同步锁\n",
    "3. lock.locked()：判断 lock 当前是否上锁，如果上锁，返回True，否则返回False【上锁失败时候的处理】\n",
    "\n",
    "---\n",
    "\n",
    "### 2.2.2.线程同步~可重入锁RLock\n",
    "\n",
    "看个场景：小明欠小张2000，欠小周5000，现在需要同时转账给他们：（规定：**几次转账加几次锁**）\n",
    "![2.RLock.png](https://images2018.cnblogs.com/blog/1127869/201808/1127869-20180824210842761-1957830831.png)\n",
    "\n",
    "小明啥也没管，直接撸起袖子就写Code了：（**错误Code示意**）\n",
    "```py\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Lock\n",
    "\n",
    "xiaoming = 8000\n",
    "xiaozhang = 3000\n",
    "xiaozhou = 5000\n",
    "\n",
    "def test(lock):\n",
    "    global xiaoming\n",
    "    global xiaozhang\n",
    "    global xiaozhou\n",
    "    # 小明想一次搞定：\n",
    "    with lock:\n",
    "        # 小明转账2000给小张\n",
    "        xiaoming -= 2000\n",
    "        xiaozhang += 2000\n",
    "        with lock:\n",
    "            # 小明转账5000给小周\n",
    "            xiaoming -= 5000\n",
    "            xiaozhou += 5000\n",
    "\n",
    "def main():\n",
    "    print(f\"[还钱前]小明{xiaoming},小张{xiaozhang},小周{xiaozhou}\")\n",
    "    lock = Lock()\n",
    "    p = ThreadPool()\n",
    "    p.apply_async(test, args=(lock, ))\n",
    "    p.close()\n",
    "    p.join()\n",
    "    print(f\"[还钱后]小明{xiaoming},小张{xiaozhang},小周{xiaozhou}\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "小明写完代码就出去了，这可把小周和小张等急了，打了N个电话来催，小明心想啥情况？\n",
    "\n",
    "一看代码楞住了，改了改代码，轻轻松松把钱转出去了：\n",
    "```py\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Lock\n",
    "\n",
    "xiaoming = 8000\n",
    "xiaozhang = 3000\n",
    "xiaozhou = 5000\n",
    "\n",
    "# 小明转账2000给小张\n",
    "def a_to_b(lock):\n",
    "    global xiaoming\n",
    "    global xiaozhang\n",
    "    with lock:\n",
    "        xiaoming -= 2000\n",
    "        xiaozhang += 2000\n",
    "\n",
    "# 小明转账5000给小周\n",
    "def a_to_c(lock):\n",
    "    global xiaoming\n",
    "    global xiaozhou\n",
    "    with lock:\n",
    "        xiaoming -= 5000\n",
    "        xiaozhou += 5000\n",
    "\n",
    "def main():\n",
    "    print(f\"[还钱前]小明{xiaoming},小张{xiaozhang},小周{xiaozhou}\")\n",
    "    lock = Lock()\n",
    "    p = ThreadPool()\n",
    "    p.apply_async(a_to_b, args=(lock, ))\n",
    "    p.apply_async(a_to_c, args=(lock, ))\n",
    "    p.close()\n",
    "    p.join()\n",
    "    print(f\"[还钱后]小明{xiaoming},小张{xiaozhang},小周{xiaozhou}\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "[还钱前]小明8000,小张3000,小周5000\n",
    "[还钱后]小明1000,小张5000,小周10000\n",
    "```\n",
    "就这么算了吗？不不不，不符合小明性格，于是小明研究了下，发现～还有个递归锁`RLock`呢，正好解决他的问题：\n",
    "```py\n",
    "from multiprocessing.dummy import Pool as ThreadPool, RLock  # 就把这边换了下\n",
    "\n",
    "xiaoming = 8000\n",
    "xiaozhang = 3000\n",
    "xiaozhou = 5000\n",
    "\n",
    "def test(lock):\n",
    "    global xiaoming\n",
    "    global xiaozhang\n",
    "    global xiaozhou\n",
    "    # 小明想一次搞定：\n",
    "    with lock:\n",
    "        # 小明转账2000给小张\n",
    "        xiaoming -= 2000\n",
    "        xiaozhang += 2000\n",
    "        with lock:\n",
    "            # 小明转账5000给小周\n",
    "            xiaoming -= 5000\n",
    "            xiaozhou += 5000\n",
    "\n",
    "def main():\n",
    "    print(f\"[还钱前]小明{xiaoming},小张{xiaozhang},小周{xiaozhou}\")\n",
    "    lock = RLock()  # 就把这边换了下\n",
    "    p = ThreadPool()\n",
    "    p.apply_async(test, args=(lock, ))\n",
    "    p.close()\n",
    "    p.join()\n",
    "    print(f\"[还钱后]小明{xiaoming},小张{xiaozhang},小周{xiaozhou}\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "RLock内部维护着一个`Lock和一个counter`变量，`counter记录了acquire`的次数，从而使得资源可以被多次`require`。直到一个线程所有的`acquire都被release`，其他的线程才能获得资源\n",
    "\n",
    "---\n",
    "\n",
    "### 2.2.3.死锁引入\n",
    "\n",
    "#### 1.多次获取导致死锁\n",
    "\n",
    "小明想到了之前说的（互斥锁`Lock`读写都加锁）就把代码拆分研究了下：\n",
    "```py\n",
    "print(\"[开始]小明转账2000给小张\")\n",
    "lock.acquire()  # 获取锁\n",
    "xiaoming -= 2000\n",
    "xiaozhang += 2000\n",
    "\n",
    "print(\"[开始]小明转账5000给小周\")\n",
    "lock.acquire()  # 获取锁（互斥锁第二次加锁）\n",
    "xiaoming -= 5000\n",
    "xiaozhou += 5000\n",
    "lock.release()  # 释放锁\n",
    "print(\"[结束]小明转账5000给小周\")\n",
    "\n",
    "lock.release()  # 释放锁\n",
    "print(\"[开始]小明转账2000给小张\")\n",
    "```\n",
    "输出发现：（第二次加锁的时候，变成阻塞等了【死锁】）\n",
    "```\n",
    "[还钱前]小明8000,小张3000,小周5000\n",
    "[开始]小明转账2000给小张\n",
    "[开始]小明转账5000给小周\n",
    "```\n",
    "**这种方式，Python提供的RLock就可以解决了**\n",
    "\n",
    "#### 2.常见的死锁\n",
    "\n",
    "看个场景：小明和小张需要流水帐，经常互刷～`小明给小张转账1000，小张给小明转账1000`\n",
    "\n",
    "一般来说，**有几个共享资源就加几把锁**（小张、小明就是两个共享资源，所以需要两把`Lock`）\n",
    "\n",
    "先描述下然后再看代码：\n",
    "\n",
    "**正常流程** 小明给小张转1000：小明自己先加个锁==>小明-1000==>获取小张的锁==>小张+1000==>转账完毕\n",
    "\n",
    "**死锁情况** 小明给小张转1000：小明自己先加个锁==>小明-1000==>准备获取小张的锁。可是这时候小张准备转账给小明，已经把自己的锁获取了，在等小明的锁（两个人相互等，于是就一直死锁了）\n",
    "\n",
    "代码模拟一下过程：\n",
    "```py\n",
    "from time import sleep\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Lock\n",
    "\n",
    "xiaoming = 5000\n",
    "xiaozhang = 8000\n",
    "m_lock = Lock() # 小明的锁\n",
    "z_lock = Lock() # 小张的锁\n",
    "\n",
    "# 小明转账1000给小张\n",
    "def a_to_b():\n",
    "    global xiaoming\n",
    "    global xiaozhang\n",
    "    global m_lock\n",
    "    global z_lock\n",
    "    with m_lock:\n",
    "        xiaoming -= 1000\n",
    "        sleep(0.01)\n",
    "        with z_lock:\n",
    "            xiaozhang += 1000\n",
    "\n",
    "# 小张转账1000给小明\n",
    "def b_to_a():\n",
    "    global xiaoming\n",
    "    global xiaozhang\n",
    "    global m_lock\n",
    "    global z_lock\n",
    "    with z_lock:\n",
    "        xiaozhang -= 1000\n",
    "        sleep(0.01)\n",
    "        with m_lock:\n",
    "            xiaoming += 1000\n",
    "\n",
    "def main():\n",
    "    print(f\"[还钱前]小明{xiaoming},小张{xiaozhang}\")\n",
    "    p = ThreadPool()\n",
    "    p.apply_async(a_to_b)\n",
    "    p.apply_async(b_to_a)\n",
    "    p.close()\n",
    "    p.join()\n",
    "    print(f\"[还钱后]小明{xiaoming},小张{xiaozhang}\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（卡在这边了）\n",
    "```\n",
    "[转账前]小明5000,小张8000\n",
    "\n",
    "```\n",
    "\n",
    "项目中像这类的情况，一般都是这几种解决方法：(还有其他解决方案，后面会继续说)\n",
    "1. **按指定顺序去访问共享资源**\n",
    "2. **trylock的重试机制**（`Lock(False)`）\n",
    "3. 在访问其他锁的时候，先把自己锁解了\n",
    "4. 得不到全部锁就先放弃已经获取的资源\n",
    "\n",
    "比如上面的情况，我们如果规定，不管是谁先转账，先从小明开始，然后再小张，那么就没问题了。或者谁钱多就谁（权重高的优先）\n",
    "```py\n",
    "from time import sleep\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Lock\n",
    "\n",
    "xiaoming = 5000\n",
    "xiaozhang = 8000\n",
    "m_lock = Lock()  # 小明的锁\n",
    "z_lock = Lock()  # 小张的锁\n",
    "\n",
    "# 小明转账1000给小张\n",
    "def a_to_b():\n",
    "    global xiaoming\n",
    "    global xiaozhang\n",
    "    global m_lock\n",
    "    global z_lock\n",
    "    # 以上次代码为例，这边只修改了这块\n",
    "    with z_lock:  # 小张权重高，大家都先获取小张的锁\n",
    "        xiaozhang += 1000\n",
    "        sleep(0.01)\n",
    "        with m_lock:\n",
    "            xiaoming -= 1000\n",
    "\n",
    "# 小张转账1000给小明\n",
    "def b_to_a():\n",
    "    global xiaoming\n",
    "    global xiaozhang\n",
    "    global m_lock\n",
    "    global z_lock\n",
    "    with z_lock:\n",
    "        xiaozhang -= 1000\n",
    "        sleep(0.01)\n",
    "        with m_lock:\n",
    "            xiaoming += 1000\n",
    "\n",
    "def main():\n",
    "    print(f\"[转账前]小明{xiaoming},小张{xiaozhang}\")\n",
    "    p = ThreadPool()\n",
    "    p.apply_async(a_to_b)\n",
    "    p.apply_async(b_to_a)\n",
    "    p.close()\n",
    "    p.join()\n",
    "    print(f\"[转账后]小明{xiaoming},小张{xiaozhang}\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "[转账前]小明5000,小张8000\n",
    "[转账后]小明5000,小张8000\n",
    "```\n",
    "\n",
    "PS：`lock.locked()`：判断 lock 当前是否上锁，如果上锁，返回True，否则返回False【上锁失败时候的处理】\n",
    "\n",
    "---\n",
    "\n",
    "### 2.2.4.线程同步~条件变量Condition\n",
    "\n",
    "**条件变量一般都不是锁，能阻塞线程，从而减少不必要的竞争**，Python内置了`RLock`（不指定就是RLock）\n",
    "\n",
    "看看源码：\n",
    "```py\n",
    "class Condition:\n",
    "    \"\"\"\n",
    "    实现条件变量的类。\n",
    "    条件变量允许一个或多个线程等到另一个线程通知它们为止\n",
    "    如果给出了lock参数而不是None，那必须是Lock或RLock对象作底层锁。\n",
    "    否则，一个新的RLock对象被创建并用作底层锁。\n",
    "    \"\"\"\n",
    "    def __init__(self, lock=None):\n",
    "        if lock is None:\n",
    "            lock = RLock()\n",
    "        self._lock = lock\n",
    "        # 设置lock的acquire（）和release（）方法\n",
    "        self.acquire = lock.acquire\n",
    "        self.release = lock.release\n",
    "```\n",
    "再看看可不可以进行with托管：（支持）\n",
    "```py\n",
    "def __enter__(self):\n",
    "    return self._lock.__enter__()\n",
    "\n",
    "def __exit__(self, *args):\n",
    "    return self._lock.__exit__(*args)\n",
    "```\n",
    "\n",
    "看个生产消费者的简单例子：(生产完就通知消费者)\n",
    "```py\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Condition\n",
    "\n",
    "s_list = []\n",
    "con = Condition()\n",
    "\n",
    "def Shop(i):\n",
    "    global con\n",
    "    global s_list\n",
    "    # 加锁保护共享资源\n",
    "    for x in range(5):\n",
    "        with con:\n",
    "            s_list.append(x)\n",
    "            print(f\"[生产者{i}]生产商品{x}\")\n",
    "            con.notify_all()  # 通知消费者有货了\n",
    "\n",
    "def User(i):\n",
    "    global con\n",
    "    global s_list\n",
    "    while True:\n",
    "        with con:\n",
    "            if s_list:\n",
    "                print(f\"列表商品：{s_list}\")\n",
    "                name = s_list.pop()  # 消费商品\n",
    "                print(f\"[消费者{i}]消费商品{name}\")\n",
    "                print(f\"列表剩余：{s_list}\")\n",
    "            else:\n",
    "                con.wait()\n",
    "\n",
    "def main():\n",
    "    p = ThreadPool()\n",
    "    # 两个生产者\n",
    "    p.map_async(Shop, range(2))\n",
    "    # 五个消费者\n",
    "    p.map_async(User, range(5))\n",
    "    p.close()\n",
    "    p.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（list之类的虽然可以不加global标示，但是为了后期维护方便，建议加上）\n",
    "```\n",
    "[生产者0]生产商品0\n",
    "[生产者0]生产商品1\n",
    "列表商品：[0, 1]\n",
    "[消费者0]消费商品1\n",
    "列表剩余：[0]\n",
    "列表商品：[0]\n",
    "[消费者0]消费商品0\n",
    "列表剩余：[]\n",
    "[生产者0]生产商品2\n",
    "列表商品：[2]\n",
    "[消费者1]消费商品2\n",
    "列表剩余：[]\n",
    "[生产者0]生产商品3\n",
    "[生产者1]生产商品0\n",
    "[生产者0]生产商品4\n",
    "列表商品：[3, 0, 4]\n",
    "[消费者1]消费商品4\n",
    "列表剩余：[3, 0]\n",
    "[生产者1]生产商品1\n",
    "[生产者1]生产商品2\n",
    "[生产者1]生产商品3\n",
    "[生产者1]生产商品4\n",
    "列表商品：[3, 0, 1, 2, 3, 4]\n",
    "[消费者2]消费商品4\n",
    "列表剩余：[3, 0, 1, 2, 3]\n",
    "列表商品：[3, 0, 1, 2, 3]\n",
    "[消费者0]消费商品3\n",
    "列表剩余：[3, 0, 1, 2]\n",
    "列表商品：[3, 0, 1, 2]\n",
    "[消费者1]消费商品2\n",
    "列表剩余：[3, 0, 1]\n",
    "列表商品：[3, 0, 1]\n",
    "[消费者3]消费商品1\n",
    "列表剩余：[3, 0]\n",
    "列表商品：[3, 0]\n",
    "[消费者3]消费商品0\n",
    "列表剩余：[3]\n",
    "列表商品：[3]\n",
    "[消费者3]消费商品3\n",
    "列表剩余：[]\n",
    "\n",
    "```\n",
    "\n",
    "通知方法：\n",
    "1. notify() ：发出资源可用的信号，唤醒任意一条因 wait(）阻塞的进程\n",
    "2. notifyAll() ：发出资源可用信号，唤醒所有因wait()阻塞的进程\n",
    "\n",
    "---\n",
    "\n",
    "### 2.2.5.线程同步~信号量Semaphore(互斥锁的高级版)\n",
    "\n",
    "记得当时在分析`multiprocessing.Queue`源码的时候，有提到过（<a href=\"http://www.cnblogs.com/dotnetcrazy/p/9426279.html#%E6%BA%90%E7%A0%81%E6%8B%93%E5%B1%95\" target=\"_blank\">点我回顾</a>）\n",
    "\n",
    "同进程的一样，`semaphore`管理一个内置的计数器，每当调用`acquire()`时内置函数`-1`，每当调用`release()`时内置函数`+1`\n",
    "\n",
    "**通俗讲就是：在互斥锁的基础上封装了下，实现一定程度的并行**\n",
    "\n",
    "举个例子，以前使用互斥锁的时候：（厕所就一个坑位，必须等里面的人出来才能让另一个人上厕所）\n",
    "![3.互斥锁.png](https://images2018.cnblogs.com/blog/1127869/201808/1127869-20180825091044646-291098504.png)\n",
    "\n",
    "**使用信号量之后：厕所坑位增加到5个（自己指定），这样可以5个人一起上厕所了==>实现了一定程度的并发**\n",
    "\n",
    "举个例子：（Python在语法这点特别爽，不用你记太多异同，功能差不多基本上代码也就差不多）\n",
    "```py\n",
    "from time import sleep\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Semaphore\n",
    "\n",
    "sem = Semaphore(5) # 限制最大连接数为5\n",
    "\n",
    "def goto_wc(i):\n",
    "    global sem\n",
    "    with sem:\n",
    "        print(f\"[线程{i}]上厕所\")\n",
    "        sleep(0.1)\n",
    "\n",
    "def main():\n",
    "    p = ThreadPool()\n",
    "    p.map_async(goto_wc, range(50))\n",
    "    p.close()\n",
    "    p.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "![4.semaphore.png](https://images2018.cnblogs.com/blog/1127869/201808/1127869-20180825094716296-130967923.png)\n",
    "\n",
    "可能看了上节回顾的会疑惑：源码里面明明是`BoundedSemaphore`，搞啥呢？\n",
    "\n",
    "其实`BoundedSemaphore`就比`Semaphore`多了个在调用`release()`时检查计数器的值是否超过了计数器的初始值，如果超过了将抛出一个异常\n",
    "\n",
    "以上一个案例说事：你换成`BoundedSemaphore`和上面效果一样==>`sem = BoundedSemaphore(5)`\n",
    "\n",
    "#### `Semaphore`补充\n",
    "\n",
    "之前有人问`Semaphore`信号量在项目中有什么应用？`(⊙o⊙)…额`，这个其实从概念就推出场景了，控制并发嘛～举个例子：\n",
    "1. 比如说我们调用免费API的时候经常看见单位时间内限制并发数在30以内，想高并发==>给钱`( ⊙ o ⊙ )捂脸`\n",
    "2. 再比如我们去爬数据的时候控制一下爬虫的并发数（`避免触发反爬虫的一种方式`,其他部分后面会逐步引入）\n",
    "\n",
    "这些虚的说完了，来个**控制并发数的案例**，然后咱们就继续并发编程的衍生了:\n",
    "```py\n",
    "import time\n",
    "from multiprocessing.dummy import threading, Semaphore\n",
    "\n",
    "class MyThread(threading.Thread):\n",
    "    def __init__(self, id, sem):\n",
    "        super().__init__()\n",
    "        self.__id = id\n",
    "        self.__sem = sem\n",
    "\n",
    "    def run(self):\n",
    "        self.__sem.acquire()  # 获取\n",
    "        self.api_test()\n",
    "\n",
    "    def api_test(self):\n",
    "        \"\"\"模拟api请求\"\"\"\n",
    "        time.sleep(1)\n",
    "        print(f\"id={self.__id}\")\n",
    "        self.__sem.release()  # 释放\n",
    "\n",
    "def main():\n",
    "    sem = Semaphore(10)  # 控制并发数\n",
    "    t_list = [MyThread(i, sem) for i in range(1000)]\n",
    "    for t in t_list:\n",
    "        t.start()\n",
    "    for t in t_list:\n",
    "        t.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出图示：\n",
    "![1.sem控制并发.gif](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180925094510613-1057170672.gif)\n",
    "\n",
    "运行分析：\n",
    "![2.sem分析.png](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180925094426568-2026746236.png)\n",
    "\n",
    "性能全图：\n",
    "![2.png](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180925094523213-1854299879.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 锁专题扩展\n",
    "\n",
    "#### 1.加锁机制\n",
    "\n",
    "**在多线程程序中，死锁问题很大一部分是由于线程同时获取多个锁造成的**，eg：一个线程获取了第一个锁，然后在获取第二个锁的 时候发生阻塞，那么这个线程就可能阻塞其他线程的执行，从而导致整个程序假死。\n",
    "\n",
    "解决死锁问题的一种方案是为程序中的每一个锁分配一个唯一的id，然后只允许按照升序规则来使用多个锁，当时举了个小明小张转账的简单例子，来避免死锁，这次咱们再看一个案例：（这个规则使用**上下文管理器**非常简单）\n",
    "\n",
    "先看看源码，咱们怎么使用：\n",
    "```py\n",
    "# 装饰器方法\n",
    "def contextmanager(func):\n",
    "    \"\"\"\n",
    "    方法格式\n",
    "    @contextmanager\n",
    "    def some_generator(<arguments>):\n",
    "        <setup>\n",
    "        try:\n",
    "            yield <value>\n",
    "        finally:\n",
    "            <cleanup>\n",
    "\n",
    "    然后就可以直接使用with托管了\n",
    "    with some_generator(<arguments>) as <variable>:\n",
    "        <body>\n",
    "    \"\"\"\n",
    "    @wraps(func)\n",
    "    def helper(*args, **kwds):\n",
    "        return _GeneratorContextManager(func, args, kwds)\n",
    "    return helper\n",
    "```\n",
    "翻译成代码就是这样了：（简化）\n",
    "```py\n",
    "from contextlib import contextmanager  # 引入上下文管理器\n",
    "\n",
    "@contextmanager\n",
    "def lock_manager(*args):\n",
    "    # 先排个序（按照id排序）\n",
    "    args = sorted(args, key=lambda x: id(x))\n",
    "\n",
    "    try:\n",
    "        for lock in args:\n",
    "            lock.acquire()\n",
    "        yield\n",
    "    finally:\n",
    "        # 先释放最后加的锁（倒序释放）\n",
    "        for lock in reversed(args):\n",
    "            lock.release()\n",
    "```\n",
    "基础忘记了可以点我（<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9175950.html#4.3.匿名函数\" target=\"_blank\">lambda</a>）\n",
    "\n",
    "以上面小明小张转账案例为例子：（不用再管锁顺序之类的了，直接全部丢进去：`with lock_manager(...)`）\n",
    "\n",
    "```py\n",
    "from contextlib import contextmanager  # 引入上下文管理器\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Lock\n",
    "\n",
    "@contextmanager\n",
    "def lock_manager(*args):\n",
    "    # 先排个序（按照id排序）\n",
    "    args = sorted(args, key=lambda x: id(x))\n",
    "\n",
    "    try:\n",
    "        for lock in args:\n",
    "            lock.acquire()\n",
    "        yield\n",
    "    finally:\n",
    "        # 先释放最后加的锁（倒序释放）\n",
    "        for lock in reversed(args):\n",
    "            lock.release()\n",
    "\n",
    "xiaoming = 5000\n",
    "xiaozhang = 8000\n",
    "m_lock = Lock()  # 小明的锁\n",
    "z_lock = Lock()  # 小张的锁\n",
    "\n",
    "# 小明转账1000给小张\n",
    "def a_to_b():\n",
    "    global xiaoming\n",
    "    global xiaozhang\n",
    "    global m_lock\n",
    "    global z_lock\n",
    "    print(f\"[转账前]小明{xiaoming},小张{xiaozhang}\")\n",
    "    with lock_manager(m_lock, z_lock):\n",
    "        xiaoming -= 1000\n",
    "        xiaozhang += 1000\n",
    "    print(f\"[转账后]小明{xiaoming},小张{xiaozhang}\")\n",
    "\n",
    "# 小张转账1000给小明\n",
    "def b_to_a():\n",
    "    global xiaoming\n",
    "    global xiaozhang\n",
    "    global m_lock\n",
    "    global z_lock\n",
    "    print(f\"[转账前]小明{xiaoming},小张{xiaozhang}\")\n",
    "    with lock_manager(m_lock, z_lock):\n",
    "        xiaozhang -= 1000\n",
    "        xiaoming += 1000\n",
    "    print(f\"[转账后]小明{xiaoming},小张{xiaozhang}\")\n",
    "\n",
    "def main():\n",
    "    print(f\"[互刷之前]小明{xiaoming},小张{xiaozhang}\")\n",
    "    p = ThreadPool()\n",
    "    for _ in range(5):\n",
    "        p.apply_async(a_to_b)\n",
    "        p.apply_async(b_to_a)\n",
    "    p.close()\n",
    "    p.join()\n",
    "    print(f\"[互刷之后]小明{xiaoming},小张{xiaozhang}\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "[互刷之前]小明5000,小张8000\n",
    "[转账前]小明5000,小张8000\n",
    "[转账前]小明5000,小张8000\n",
    "[转账后]小明4000,小张9000\n",
    "[转账前]小明5000,小张8000\n",
    "[转账后]小明5000,小张8000\n",
    "[转账前]小明5000,小张8000\n",
    "[转账前]小明4000,小张9000\n",
    "[转账后]小明4000,小张9000\n",
    "[转账后]小明5000,小张8000\n",
    "[转账前]小明5000,小张8000\n",
    "[转账后]小明4000,小张9000\n",
    "[转账前]小明4000,小张9000\n",
    "[转账前]小明4000,小张9000\n",
    "[转账后]小明5000,小张8000\n",
    "[转账前]小明5000,小张8000\n",
    "[转账后]小明4000,小张9000\n",
    "[转账后]小明5000,小张8000\n",
    "[转账前]小明5000,小张8000\n",
    "[转账后]小明4000,小张9000\n",
    "[转账后]小明5000,小张8000\n",
    "[互刷之后]小明5000,小张8000\n",
    "```\n",
    "再来个验证，在他们互刷的过程中，小潘还了1000元给小明\n",
    "```py\n",
    "from time import sleep\n",
    "from contextlib import contextmanager  # 引入上下文管理器\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Lock\n",
    "\n",
    "@contextmanager\n",
    "def lock_manager(*args):\n",
    "    # 先排个序（按照id排序）\n",
    "    args = sorted(args, key=lambda x: id(x))\n",
    "\n",
    "    try:\n",
    "        for lock in args:\n",
    "            lock.acquire()\n",
    "        yield\n",
    "    finally:\n",
    "        # 先释放最后加的锁（倒序释放）\n",
    "        for lock in reversed(args):\n",
    "            lock.release()\n",
    "\n",
    "xiaopan = 9000\n",
    "xiaoming = 5000\n",
    "xiaozhang = 8000\n",
    "m_lock = Lock()  # 小明的锁\n",
    "z_lock = Lock()  # 小张的锁\n",
    "p_lock = Lock()  # 小潘的锁\n",
    "\n",
    "# 小明转账1000给小张\n",
    "def a_to_b():\n",
    "    global xiaoming\n",
    "    global xiaozhang\n",
    "    global m_lock\n",
    "    global z_lock\n",
    "    print(f\"[转账前]小明{xiaoming},小张{xiaozhang}\")\n",
    "    with lock_manager(m_lock, z_lock):\n",
    "        xiaoming -= 1000\n",
    "        xiaozhang += 1000\n",
    "    print(f\"[转账后]小明{xiaoming},小张{xiaozhang}\")\n",
    "\n",
    "# 小张转账1000给小明\n",
    "def b_to_a():\n",
    "    global xiaoming\n",
    "    global xiaozhang\n",
    "    global m_lock\n",
    "    global z_lock\n",
    "    print(f\"[转账前]小明{xiaoming},小张{xiaozhang}\")\n",
    "    with lock_manager(m_lock, z_lock):\n",
    "        xiaozhang -= 1000\n",
    "        xiaoming += 1000\n",
    "    print(f\"[转账后]小明{xiaoming},小张{xiaozhang}\")\n",
    "\n",
    "\n",
    "# 小潘还1000给小明\n",
    "def c_to_a():\n",
    "    global xiaoming\n",
    "    global xiaopan\n",
    "    global m_lock\n",
    "    global p_lock\n",
    "    print(f\"[转账前]小明{xiaoming},小潘{xiaopan}\")\n",
    "    with lock_manager(m_lock, p_lock):\n",
    "        xiaopan -= 1000\n",
    "        xiaoming += 1000\n",
    "    print(f\"[转账后]小明{xiaoming},小潘{xiaopan}\")\n",
    "\n",
    "def main():\n",
    "    print(f\"[互刷之前]小明{xiaoming},小张{xiaozhang},小潘{xiaopan}\")\n",
    "    p = ThreadPool()\n",
    "    for _ in range(5):\n",
    "        p.apply_async(a_to_b)\n",
    "        # 在他们互刷的过程中，小潘还了1000元给小明\n",
    "        if _ == 3:\n",
    "            p.apply_async(c_to_a)\n",
    "        p.apply_async(b_to_a)\n",
    "    p.close()\n",
    "    p.join()\n",
    "    print(f\"[互刷之后]小明{xiaoming},小张{xiaozhang},小潘{xiaopan}\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "[互刷之前]小明5000,小张8000,小潘9000\n",
    "[转账前]小明5000,小张8000\n",
    "[转账前]小明5000,小张8000\n",
    "[转账后]小明4000,小张9000\n",
    "[转账前]小明5000,小张8000\n",
    "[转账前]小明4000,小张9000\n",
    "[转账后]小明5000,小张8000\n",
    "[转账前]小明5000,小张8000\n",
    "[转账后]小明4000,小张9000\n",
    "[转账后]小明5000,小张8000\n",
    "[转账前]小明5000,小张8000\n",
    "[转账后]小明4000,小张9000\n",
    "[转账前]小明4000,小张9000\n",
    "[转账前]小明4000,小潘9000 # 注意下这个\n",
    "[转账后]小明5000,小张8000\n",
    "[转账前]小明5000,小张8000\n",
    "[转账后]小明4000,小张9000\n",
    "[转账后]小明5000,小潘8000 # 注意下这个\n",
    "[转账前]小明5000,小张9000\n",
    "[转账后]小明6000,小张8000\n",
    "[转账后]小明5000,小张9000\n",
    "[转账前]小明6000,小张8000\n",
    "[转账后]小明6000,小张8000\n",
    "[互刷之后]小明6000,小张8000,小潘8000\n",
    "```\n",
    "\n",
    "#### 上下文管理器进一步完善\n",
    "```py\n",
    "from contextlib import contextmanager\n",
    "from multiprocessing.dummy import threading # or import threading\n",
    "\n",
    "# ThreadLocal 下节会说\n",
    "_local = threading.local()\n",
    "\n",
    "@contextmanager\n",
    "def acquire(*args):\n",
    "    # 以id将锁进行排序\n",
    "    args = sorted(args, key=lambda x: id(x))\n",
    "\n",
    "    # 确保不违反以前获取的锁顺序\n",
    "    acquired = getattr(_local, 'acquired', [])\n",
    "    if acquired and max(id(lock) for lock in acquired) >= id(args[0]):\n",
    "        raise RuntimeError('锁顺序有问题')\n",
    "\n",
    "    # 获取所有锁\n",
    "    acquired.extend(args)\n",
    "    _local.acquired = acquired  # ThreadLocal：每个线程独享acquired\n",
    "\n",
    "    # 固定格式\n",
    "    try:\n",
    "        for lock in args:\n",
    "            lock.acquire()\n",
    "        yield\n",
    "    finally:\n",
    "        # 逆向释放锁资源\n",
    "        for lock in reversed(args):\n",
    "            lock.release()\n",
    "        # 把释放掉的锁给删了\n",
    "        del acquired[-len(args):]\n",
    "```\n",
    "\n",
    "#### 2.哲学家吃面\n",
    "\n",
    "先看看场景：五个外国哲学家到中国来吃饭了，因为不了解行情，每个人只拿了一双筷子，然后点了一大份的面。碍于面子，他们不想再去拿筷子了，于是就想通过脑子来解决这个问题。\n",
    "\n",
    "每个哲学家吃面都是需要两只筷子的，这样问题就来了：（只能拿自己两手边的筷子）\n",
    "1. 如果大家都是先拿自己筷子，再去抢别人的筷子，那么就都等着饿死了（**死锁**）\n",
    "2. 如果有一个人打破这个常规，先拿别人的筷子再拿自己的，那么肯定有一个人可以吃到面了\n",
    "3. 5个筷子，意味着最好的情况 ==> 同一时刻有2人在吃（0人，1人，2人）\n",
    "\n",
    "把现实问题转换成代码就是：\n",
    "1. 哲学家--线程\n",
    "2. 筷子--资源（几个资源对应几把锁）\n",
    "3. 吃完一口面就放下筷子--lock的释放\n",
    "\n",
    "有了上面基础这个就简单了，使用死锁避免机制解决**哲学家就餐问题**的实现：（不用再操心锁顺序了）\n",
    "```py\n",
    "from contextlib import contextmanager  # 引入上下文管理器\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Lock, current_process as current_thread\n",
    "\n",
    "# 使用简化版，便于你们理解\n",
    "@contextmanager\n",
    "def lock_manager(*args):\n",
    "    # 先排个序（按照id排序）\n",
    "    args = sorted(args, key=lambda x: id(x))\n",
    "\n",
    "    try:\n",
    "        # 依次加锁\n",
    "        for lock in args:\n",
    "            lock.acquire()\n",
    "        yield\n",
    "    finally:\n",
    "        # 先释放最后加的锁（倒序释放）\n",
    "        for lock in reversed(args):\n",
    "            lock.release()\n",
    "\n",
    "#########################################\n",
    "\n",
    "def eat(l_lock, r_lock):\n",
    "    while True:\n",
    "        with lock_manager(l_lock, r_lock):\n",
    "            # 获取当前线程的名字\n",
    "            print(f\"{current_thread().name}，正在吃面\")\n",
    "            sleep(0.5)\n",
    "\n",
    "def main():\n",
    "    resource = 5  # 5个筷子，5个哲学家\n",
    "    locks = [Lock() for i in range(resource)]  # 几个资源几个锁\n",
    "    \n",
    "    p = ThreadPool(resource) # 让线程池里面有5个线程（默认是cup核数）\n",
    "    for i in range(resource):\n",
    "        # 抢左手筷子（locks[i]）和右手的筷子（locks[(i + 1) % resource]）\n",
    "        # 举个例子更清楚：i=0 ==> 0,1；i=4 ==> 4,0\n",
    "        p.apply_async(eat, args=(locks[i], locks[(i + 1) % resource]))\n",
    "    p.close()\n",
    "    p.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出图示：\n",
    "![5.哲学家](https://images2018.cnblogs.com/blog/1127869/201809/1127869-20180906153955421-825585843.gif)\n",
    "\n",
    "### 自行拓展\n",
    "\n",
    "#### 1.银行家算法\n",
    "\n",
    "PS：这个一般都是操作系统的算法，了解下就可以了，上面哲学家吃面用的更多一点（欢迎投稿～）\n",
    "\n",
    "我们可以把操作系统看作是银行家，操作系统管理的资源相当于银行家管理的资金，进程向操作系统请求分配资源相当于用户向银行家贷款。\n",
    "为保证资金的安全，银行家规定：\n",
    "1. 当一个顾客对资金的最大需求量不超过银行家现有的资金时就可接纳该顾客；\n",
    "2. 顾客可以分期贷款，但贷款的总数不能超过最大需求量；\n",
    "3. 当银行家现有的资金不能满足顾客尚需的贷款数额时，对顾客的贷款可推迟支付，但总能使顾客在有限的时间里得到贷款；\n",
    "4. 当顾客得到所需的全部资金后，一定能在有限的时间里归还所有的资金.\n",
    "\n",
    "操作系统按照银行家制定的规则为进程分配资源，当进程首次申请资源时，要测试该进程对资源的最大需求量，如果系统现存的资源可以满足它的最大需求量则按当前的申请量分配资源，否则就推迟分配。当进程在执行中继续申请资源时，先测试该进程本次申请的资源数是否超过了该资源所剩余的总量。若超过则拒绝分配资源，若能满足则按当前的申请量分配资源，否则也要推迟分配。\n",
    "\n",
    "---\n",
    "\n",
    "通俗讲就是：当一个进程申请使用资源的时候，银行家算法通过先试探分配给该进程资源，然后通过安全性算法判断分配后的系统是否处于安全状态，若不安全则试探分配作废，让该进程继续等待。\n",
    "\n",
    "参考链接：\n",
    "```\n",
    "https://www.cnblogs.com/chuxiuhong/p/6103928.html\n",
    "https://www.cnblogs.com/Lynn-Zhang/p/5672080.html\n",
    "https://blog.csdn.net/qq_33414271/article/details/80245715\n",
    "https://blog.csdn.net/qq_37315403/article/details/82179707\n",
    "```\n",
    "\n",
    "#### 2.读写锁\n",
    "\n",
    "Python里面没找到读写锁，这个应用场景也是有的，先简单说说这个概念，你可以结合`RLock`实现读写锁（了解下，用到再研究）\n",
    "\n",
    "**读写锁**（一把锁）：\n",
    "1. 读共享：A加读锁，B、C想要加读锁==>成功（并行操作）\n",
    "2. 写独占：A加写锁，B、C想要读（写）==>阻塞等\n",
    "3. 读写不能同时（写优先级高）：A读，B要写，C要读，D要写==>A读了，B在写，C等B写完读，D等C读完写（读写不能同时进行）\n",
    "\n",
    "扩展参考：\n",
    "\n",
    "<a href=\"http://xiaorui.cc/?p=2384\" target=\"_blank\">http://xiaorui.cc/?p=2384</a>\n",
    "\n",
    "<a href=\"https://www.jb51.net/article/82999.htm\" target=\"_blank\">https://www.jb51.net/article/82999.htm</a>\n",
    "\n",
    "<a href=\"https://blog.csdn.net/11b202/article/details/11478635\" target=\"_blank\">https://blog.csdn.net/11b202/article/details/11478635</a>\n",
    "\n",
    "<a href=\"https://blog.csdn.net/vcbin/article/details/51181121\" target=\"_blank\">https://blog.csdn.net/vcbin/article/details/51181121</a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 扩展：线程安全\n",
    "\n",
    "上次说了锁相关，把问题稍微汇聚提炼一下～重点在思想，语言无差别\n",
    "\n",
    "### 1.安全终止线程\n",
    "\n",
    "正常执行线程任务没什么好说的，可以通过`isAlive`判断当前线程状态，对于耗时操作可以设置超时时间`t.join(timeout=1)`+重试机制\n",
    "\n",
    "但是后台线程`Thread(daemon=True)`就没那么好控制了：**这些线程会在主线程终止时自动销毁**。除了如上所示的两个操作，并没有太多可以对线程做的事情（无法结束一个线程，无法给它发送信号，无法调整它的调度，也无法执行其他高级操作）\n",
    "\n",
    "#### 通用：寻常线程\n",
    "\n",
    "比如说，如果你需要在**不终止主线程的情况下杀死线程**，那么这个线程就不能通过`daemon`的方式了，必须通过编程在某个特定点**轮询来退出**：\n",
    "```py\n",
    "from time import sleep\n",
    "from multiprocessing.dummy import threading\n",
    "\n",
    "class MyThread(threading.Thread):\n",
    "    def __init__(self):\n",
    "        self.__running = True\n",
    "        super().__init__()\n",
    "\n",
    "    def terminate(self):\n",
    "        self.__running = False\n",
    "\n",
    "    def run(self):\n",
    "        # 轮询方式必须根据业务来，不然没有意义\n",
    "        while self.__running:\n",
    "            print(\"do something\")\n",
    "            sleep(2)\n",
    "def main():\n",
    "    t = MyThread()\n",
    "    t.start()\n",
    "    t.terminate() # 调用的时候可以通过`terminate`来结束线程\n",
    "    t.join()\n",
    "    # t.join(timeout=1)  # 超时时间\n",
    "    print(\"over\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（再提醒一下，轮循必须根据业务来，不管是重试机制还是其他，这边只是举个例子）\n",
    "```\n",
    "do something\n",
    "over\n",
    "```\n",
    "上面这种方式，比较好理解，但是比较依赖`threading.Thread`，项目里面一般这么改下：\n",
    "```py\n",
    "from time import sleep\n",
    "from multiprocessing.dummy import threading\n",
    "\n",
    "class ShutdownTask(object):\n",
    "    def __init__(self):\n",
    "        self.__running = True\n",
    "\n",
    "    def terminate(self):\n",
    "        self.__running = False\n",
    "\n",
    "    def run(self):\n",
    "        # 轮询方式必须根据业务来，不然没有意义\n",
    "        while self.__running:\n",
    "            print(\"do something\")\n",
    "            sleep(2)\n",
    "\n",
    "def main():\n",
    "    task = ShutdownTask()\n",
    "    t = threading.Thread(target=task.run)\n",
    "    t.start()\n",
    "    task.terminate()  # 结束线程\n",
    "    t.join()\n",
    "    print(\"over\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（`ShutdownTask`就解耦了，不依赖`threading`库了，你放在进程中使用也没事了）\n",
    "```\n",
    "do something\n",
    "over\n",
    "```\n",
    "\n",
    "#### 通用：阻塞线程\n",
    "\n",
    "是不是心想着现在都妥妥的了？但是遗憾的是～如果遇到了**IO阻塞的情况，轮循形同虚设**，这时候就需要超时时间来解决了：\n",
    "1. join(timeout)是一种方式\n",
    "2. socket的超时机制也是一种方式（后面会探讨）\n",
    "\n",
    "伪代码实现：（**加上重试机制更完善**）\n",
    "```py\n",
    "class IOTask:\n",
    "    def __init__(self):\n",
    "        self.__running = True\n",
    "\n",
    "    def terminate(self):\n",
    "        self.__running = False\n",
    "\n",
    "    def run(self, socket):\n",
    "        socket.settimeout(3)  # 设置超时时间\n",
    "        while self.__running:\n",
    "            try:\n",
    "                print(\"正在忙.....\")\n",
    "                socket.recv(8192)\n",
    "                sleep(1)\n",
    "                break\n",
    "            except Exception:\n",
    "                print(\"超时处理\")\n",
    "                break\n",
    "```\n",
    "由于全局解释锁（GIL）的原因，Python 的线程被限制到同一时刻只允许一个线程执行这样一个执行模型。所以，Python 的线程更适用于处理I/O和其他需要并发执行的阻塞操作（比如等待I/O、等待从数据库获取数据等等），而不是需要多处理器并行的计算密集型任务。【这也是为什么我说Python和其他语言并发编程的重点不一样：`进程+协程`】\n",
    "\n",
    "---\n",
    "\n",
    "#### 特有：进程安全退出\n",
    "\n",
    "Python进程`Process`可以通过：`terminate()` or `signal`的方式终止：（<a href=\"http://www.cnblogs.com/dotnetcrazy/p/9363810.html\" target=\"_blank\">点我回顾</a>）\n",
    "\n",
    "`terminate`联合`signal`进行退出前处理：\n",
    "```py\n",
    "from time import sleep\n",
    "from signal import signal, SIGTERM\n",
    "from multiprocessing import Process\n",
    "\n",
    "# 可以释放锁、记录日记之类的操作\n",
    "def save_data(signalnum, frame):\n",
    "    print(f\"[退出前处理]signalnum:{signalnum},frame:{frame}\")\n",
    "    exit(0)\n",
    "\n",
    "def test():\n",
    "    # 信号处理\n",
    "    signal(SIGTERM, save_data)\n",
    "    print(\"subProcess start\")\n",
    "    sleep(2)\n",
    "    print(\"subProcess over\")\n",
    "\n",
    "def main():\n",
    "    p = Process(target=test)\n",
    "    p.start()\n",
    "    sleep(1)\n",
    "    p.terminate()  # 进程结束\n",
    "    p.join()\n",
    "    print(\"mainProcess over\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```py\n",
    "subProcess start\n",
    "[退出前处理]signalnum:15,frame:<frame object at 0x7f27df6c6210>\n",
    "mainProcess over\n",
    "```\n",
    "还有一种方式，通过进程间状态共享（<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9426279.html#1.6.进程间状态共享\" target=\"_blank\">点我回顾</a>），实现优雅的退出子进程\n",
    "\n",
    "---\n",
    "\n",
    "### 2.线程共享安全\n",
    "\n",
    "这块上面说很多了，再介绍几种：\n",
    "1. CAS原子类(Java比较常用)\n",
    "2. Thread Local(常用场景：存各种的连接池)\n",
    "4. Lock，互斥锁，可重入锁（递归锁）,信号量，条件变量（上面都在说这些）\n",
    "\n",
    "在多线程环境下，每个线程都有自己的数据，想要互不干扰又不想定义成局部变量传来传去，怎么办？\n",
    "\n",
    "一开始是这么解决的：\n",
    "```py\n",
    "from multiprocessing.dummy import threading\n",
    "\n",
    "global_dict = {}\n",
    "\n",
    "def task1():\n",
    "    # 根据当前线程查找：\n",
    "    global_dict[threading.current_thread()] = 10\n",
    "    global_dict[threading.current_thread()] += 10\n",
    "\n",
    "def task2():\n",
    "    # 根据当前线程查找：\n",
    "    global_dict[threading.current_thread()] = 10\n",
    "    global_dict[threading.current_thread()] -= 10\n",
    "\n",
    "def main():\n",
    "    t1 = threading.Thread(target=task1)\n",
    "    t2 = threading.Thread(target=task2)\n",
    "    t1.start()\n",
    "    t2.start()\n",
    "    t1.join()\n",
    "    t2.join()\n",
    "\n",
    "    print(global_dict)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "但这么搞也很麻烦，于是就有了`ThreadLocal`：\n",
    "```py\n",
    "from multiprocessing.dummy import threading\n",
    "\n",
    "global_local = threading.local()\n",
    "\n",
    "def show_name():\n",
    "    print(f\"[{threading.current_thread().name}]{global_local.name}\")\n",
    "\n",
    "def task1():\n",
    "    global_local.name = \"小明\"\n",
    "    show_name()\n",
    "\n",
    "def task2():\n",
    "    global_local.name = \"小张\"\n",
    "    show_name()\n",
    "\n",
    "def main():\n",
    "    t1 = threading.Thread(target=task1)\n",
    "    t2 = threading.Thread(target=task2)\n",
    "    t1.start()\n",
    "    t2.start()\n",
    "    t1.join()\n",
    "    t2.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（同样存的是name属性，不同线程间互不影响）\n",
    "```\n",
    "[Thread-1]小明\n",
    "[Thread-2]小张\n",
    "```\n",
    "\n",
    "#### 导航\n",
    "\n",
    "再来谈谈常用的两种死锁解决思路：（这次不仅仅局限在`Python`了）\n",
    "1. \"顺序锁\"\n",
    "2. `tryLock`\n",
    "\n",
    "说说顺序锁的算法：`hash Sort`(3种情况)，先看看几种hash的对比吧："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 3 µs, sys: 1 µs, total: 4 µs\n",
      "Wall time: 9.3 µs\n",
      "是否相等：False\n",
      "<unlocked _thread.lock object at 0x7fdc5d7bd9e0>\n",
      "<unlocked _thread.lock object at 0x7fdc640f2878>\n"
     ]
    }
   ],
   "source": [
    "%time\n",
    "from multiprocessing.dummy import Lock\n",
    "\n",
    "m_lock = Lock()\n",
    "z_lock = Lock()\n",
    "print(f\"是否相等：{m_lock==z_lock}\\n{m_lock}\\n{z_lock}\")  # 地址不一样"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 2 µs, sys: 0 ns, total: 2 µs\n",
      "Wall time: 5.48 µs\n",
      "是否相等：False\n",
      "8786527370654\n",
      "-9223363250320510329\n"
     ]
    }
   ],
   "source": [
    "%time\n",
    "\n",
    "m_code = hash(m_lock)\n",
    "z_code = hash(z_lock)\n",
    "print(f\"是否相等：{m_code==z_code}\\n{m_code}\\n{z_code}\")  # 值一样"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 3 µs, sys: 0 ns, total: 3 µs\n",
      "Wall time: 5.25 µs\n",
      "是否相等：False\n",
      "f330fa642adfe965795dc5e88df13f21deff8afc\n",
      "3ef62508c341fe5c6f3595cd6e1864d3b4ae9f28\n"
     ]
    }
   ],
   "source": [
    "%time\n",
    "\n",
    "from hashlib import sha1\n",
    "\n",
    "# Java可以使用：identityhashcode\n",
    "m_code = sha1(str(m_lock).encode(\"utf-8\")).hexdigest()\n",
    "z_code = sha1(str(z_code).encode(\"utf-8\")).hexdigest()\n",
    "print(f\"是否相等：{m_code==z_code}\\n{m_code}\\n{z_code}\")  # 不相等"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 2 µs, sys: 1 µs, total: 3 µs\n",
      "Wall time: 5.01 µs\n",
      "是否相等：False\n",
      "140584437930464\n",
      "140584548247672\n"
     ]
    }
   ],
   "source": [
    "%time\n",
    "\n",
    "m_code = id(m_lock)\n",
    "z_code = id(z_lock)\n",
    "print(f\"是否相等：{m_code==z_code}\\n{m_code}\\n{z_code}\")  # 不相等"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 动态死锁\n",
    "\n",
    "如果是一般的顺序死锁，那么程序代码改改逻辑基本上就可以避免了。比如调试的时候就知晓，或者借助类似于`jstack` or 开发工具查看：\n",
    "![6.死锁调试.gif](https://images2018.cnblogs.com/blog/1127869/201809/1127869-20180911190211373-1356084841.gif)\n",
    "\n",
    "怕就怕在动态上==>举个例子：（还是小明小张互刷的案例）\n",
    "\n",
    "有人实践后很多疑问，说明明我就按照顺序加锁了啊，先加转出账号，再加锁转入账号？\n",
    "\n",
    "其实...换位思考就懂了==>伪代码\n",
    "```py\n",
    "def transfer(p_from, p_to, money):\n",
    "    with p_from.lock:\n",
    "        p_from.money -= money\n",
    "        ......\n",
    "        with p_to.lock:\n",
    "            p_to += money\n",
    "```\n",
    "这个虽然按照了所谓的顺序，但是转帐人其实在变，也就变成了动态的，所以也会出现死锁：\n",
    "```py\n",
    "from time import sleep\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Lock\n",
    "\n",
    "class People(object):\n",
    "    def __init__(self, name, money=5000):\n",
    "        self.name = name\n",
    "        self.lock = Lock()\n",
    "        self.money = money  # 设置一个初始金额\n",
    "\n",
    "def transfer(p_from, p_to, money):\n",
    "    with p_from.lock:\n",
    "        p_from.money -= money\n",
    "        sleep(1)  # 模拟网络延迟\n",
    "        with p_to.lock:\n",
    "            p_to += money\n",
    "\n",
    "def main():\n",
    "    xiaoming = People(\"小明\")\n",
    "    xiaozhang = People(\"小张\")\n",
    "    print(f\"[互刷前]小明：{xiaoming.money},小张：{xiaozhang.money}\")\n",
    "\n",
    "    p = ThreadPool()\n",
    "    p.apply_async(transfer, args=(xiaoming, xiaozhang, 1000))\n",
    "    p.apply_async(transfer, args=(xiaozhang, xiaoming, 1000))\n",
    "    p.close()\n",
    "    p.join()\n",
    "\n",
    "    print(f\"[互刷后]小明：{xiaoming.money},小张：{xiaozhang.money}\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（死锁了，联想哲学家吃面～每个人先拿自己的筷子再抢人的筷子）\n",
    "```\n",
    "[互刷前]小明：5000,小张：5000\n",
    "\n",
    "```\n",
    "\n",
    "**解决方案**～伪代码思路：\n",
    "```py\n",
    "def transfer(cls, p_from, p_to, money):\n",
    "    \"\"\"p_from：谁转账,p_to：转给谁,money:转多少\"\"\"\n",
    "    from_hash = get_hash(p_from)\n",
    "    to_hash = get_hash(p_to)\n",
    "\n",
    "    # 规定：谁大先锁谁\n",
    "    if from_hash > to_hash:\n",
    "        with p_from.lock:\n",
    "            p_from.money -= money\n",
    "            sleep(1)  # 模拟网络延迟\n",
    "            with p_to.lock:\n",
    "                p_to.money += money\n",
    "    elif from_hash < to_hash:\n",
    "        with p_to.lock:\n",
    "            p_to.money += money\n",
    "            sleep(1)  # 模拟网络延迟\n",
    "            with p_from.lock:\n",
    "                p_from.money -= money\n",
    "    # hash出现碰撞时处理：（可能性很低）\n",
    "    else:\n",
    "        # 平局的时候，大家一起抢一个中间锁，谁抢到谁先转账\n",
    "        with cls.tie_lock:\n",
    "            with p_from.lock:\n",
    "                p_from.money -= money\n",
    "                sleep(1)  # 模拟网络延迟\n",
    "                with p_to.lock:\n",
    "                    p_to.money += money\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "完整Python代码示意：\n",
    "```py\n",
    "from time import sleep\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Lock\n",
    "\n",
    "class Account(object):\n",
    "    def __init__(self, name, money=5000):\n",
    "        self.name = name\n",
    "        self.lock = Lock()\n",
    "        self.money = money  # 设置一个初始金额\n",
    "\n",
    "class Bank(object):\n",
    "    tie_lock = Lock()\n",
    "\n",
    "    @classmethod\n",
    "    def __get_hash(cls, obj):\n",
    "        return id(obj)  # hash_func(obj)\n",
    "\n",
    "    @classmethod\n",
    "    def transfer(cls, p_from, p_to, money):\n",
    "        \"\"\"p_from：谁转账,p_to：转给谁,money:转多少\"\"\"\n",
    "        from_hash = cls.__get_hash(p_from)\n",
    "        to_hash = cls.__get_hash(p_to)\n",
    "\n",
    "        print(f\"from:{p_from.name}to{p_to.name}=>{money}\")\n",
    "        # 规定：谁大先锁谁\n",
    "        if from_hash > to_hash:\n",
    "            print(\"from_hash > to_hash\")\n",
    "            with p_from.lock:\n",
    "                p_from.money -= money\n",
    "                sleep(1)  # 模拟网络延迟\n",
    "                with p_to.lock:\n",
    "                    p_to.money += money\n",
    "        elif from_hash < to_hash:\n",
    "            print(\"from_hash < to_hash\")\n",
    "            with p_to.lock:\n",
    "                p_to.money += money\n",
    "                sleep(1)  # 模拟网络延迟\n",
    "                with p_from.lock:\n",
    "                    p_from.money -= money\n",
    "        # hash出现碰撞时处理：（可能性很低）\n",
    "        else:\n",
    "            print(\"from_hash < to_hash\")\n",
    "            # 平局的时候，大家一起抢一个中间锁，谁抢到谁先转账\n",
    "            with cls.tie_lock:\n",
    "                with p_from.lock:\n",
    "                    p_from.money -= money\n",
    "                    sleep(1)  # 模拟网络延迟\n",
    "                    with p_to.lock:\n",
    "                        p_to.money += money\n",
    "def main():\n",
    "    xiaoming = Account(\"小明\")\n",
    "    xiaozhang = Account(\"小张\")\n",
    "    xiaopan = Account(\"小潘\")\n",
    "    print(f\"[互刷前]小明：{xiaoming.money},小张：{xiaozhang.money},小潘{xiaopan.money}\")\n",
    "\n",
    "    p = ThreadPool()\n",
    "    for i in range(3):\n",
    "        p.apply_async(Bank.transfer, args=(xiaoming, xiaozhang, 1000))\n",
    "        if i == 1:  # 小潘突然间还了1000给小明\n",
    "            p.apply_async(Bank.transfer, args=(xiaopan, xiaoming, 1000))\n",
    "        p.apply_async(Bank.transfer, args=(xiaozhang, xiaoming, 1000))\n",
    "    p.close()\n",
    "    p.join()\n",
    "\n",
    "    print(f\"[互刷后]小明：{xiaoming.money},小张：{xiaozhang.money},小潘{xiaopan.money}\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "[互刷前]小明：5000,小张：5000,小潘5000\n",
    "from:小明to小张=>1000\n",
    "from_hash < to_hash\n",
    "from:小张to小明=>1000\n",
    "from:小明to小张=>1000\n",
    "from_hash > to_hash\n",
    "from_hash < to_hash\n",
    "from:小潘to小明=>1000\n",
    "from_hash < to_hash\n",
    "from:小张to小明=>1000\n",
    "from:小明to小张=>1000\n",
    "from_hash > to_hash\n",
    "from_hash < to_hash\n",
    "from:小张to小明=>1000\n",
    "from_hash > to_hash\n",
    "[互刷后]小明：6000,小张：5000,小潘4000\n",
    "```\n",
    "![7.test1.png](https://images2018.cnblogs.com/blog/1127869/201809/1127869-20180912093231383-1903160113.png)\n",
    "![7.test2.png](https://images2018.cnblogs.com/blog/1127869/201809/1127869-20180912093304951-1716191905.png)\n",
    "\n",
    "`Python`上下文管理器我就不说了，上面说过了，思路和“顺序锁”基本一样：\n",
    "```py\n",
    "from contextlib import contextmanager\n",
    "from multiprocessing.dummy import threading # or import threading\n",
    "\n",
    "_local = threading.local()\n",
    "\n",
    "@contextmanager\n",
    "def acquire(*args):\n",
    "    # 以id将锁进行排序\n",
    "    args = sorted(args, key=lambda x: id(x))\n",
    "\n",
    "    # 确保不违反以前获取的锁顺序\n",
    "    acquired = getattr(_local, 'acquired', [])\n",
    "    if acquired and max(id(lock) for lock in acquired) >= id(args[0]):\n",
    "        raise RuntimeError('锁顺序有问题')\n",
    "\n",
    "    # 获取所有锁\n",
    "    acquired.extend(args)\n",
    "    _local.acquired = acquired  # ThreadLocal：每个线程独享acquired\n",
    "\n",
    "    # 固定格式\n",
    "    try:\n",
    "        for lock in args:\n",
    "            lock.acquire()\n",
    "        yield\n",
    "    finally:\n",
    "        # 逆向释放锁资源\n",
    "        for lock in reversed(args):\n",
    "            lock.release()\n",
    "        # 把释放掉的锁给删了\n",
    "        del acquired[-len(args):]\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "### 活锁\n",
    "\n",
    "大家都听说过死锁deadlock，但是很少有人听说过活锁livelock。活锁主要由两个线程过度谦让造成，两个线程都想让对方先干话，结果反而都无法继续执行下去。因为两个线程都在活跃状态，故称活锁。\n",
    "\n",
    "#### trylock\n",
    "\n",
    "`trylock`可以解决死锁问题，但是用不好也会出现少见的活锁问题：\n",
    "```py\n",
    "from time import sleep\n",
    "from random import random\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Lock\n",
    "\n",
    "\n",
    "class People(object):\n",
    "    def __init__(self, name, money=5000):\n",
    "        self.name = name\n",
    "        self.lock = Lock()  # 非阻塞等\n",
    "        self.money = money  # 设置一个初始金额\n",
    "\n",
    "\n",
    "def transfer(p_from, p_to, money):\n",
    "    flag = True\n",
    "    while flag:\n",
    "        # 尝试获取p_from.lock\n",
    "        if p_from.lock.acquire(False):  # 非阻塞\n",
    "            try:\n",
    "                sleep(1)  # 模拟网络延迟\n",
    "                # 尝试获取p_to.lock\n",
    "                if p_to.lock.acquire(False):\n",
    "                    try:\n",
    "                        p_from.money -= money\n",
    "                        p_to.money += money\n",
    "                        flag = False\n",
    "                    finally:\n",
    "                        print(\"p_to release\")\n",
    "                        p_to.lock.release()  # 释放锁\n",
    "            finally:\n",
    "                p_from.lock.release()  # 释放锁\n",
    "        sleep(random())  # 随机睡[0,1)s\n",
    "\n",
    "def main():\n",
    "    xiaoming = People(\"小明\")\n",
    "    xiaozhang = People(\"小张\")\n",
    "    xiaopan = People(\"小潘\")\n",
    "    print(f\"[互刷前]小明：{xiaoming.money},小张：{xiaozhang.money},小潘：{xiaopan.money}\")\n",
    "\n",
    "    p = ThreadPool()\n",
    "    for i in range(3):\n",
    "        p.apply_async(transfer, args=(xiaoming, xiaozhang, 1000))\n",
    "        if i == 1:\n",
    "            p.apply_async(transfer, args=(xiaopan, xiaoming, 1000))\n",
    "        p.apply_async(transfer, args=(xiaozhang, xiaoming, 1000))\n",
    "    p.close()\n",
    "    p.join()\n",
    "\n",
    "    print(f\"[互刷后]小明：{xiaoming.money},小张：{xiaozhang.money},小潘：{xiaopan.money}\")\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（没有`sleep(random())  # 随机睡[0,1)s`就是一个活锁了）\n",
    "```\n",
    "[互刷前]小明：5000,小张：5000,小潘：5000\n",
    "p_to release\n",
    "p_to release\n",
    "p_to release\n",
    "p_to release\n",
    "p_to release\n",
    "p_to release\n",
    "[互刷后]小明：6000,小张：5000,小潘：4000\n",
    "```\n",
    "![8.test1.png](https://images2018.cnblogs.com/blog/1127869/201809/1127869-20180912093035157-1714015198.png)\n",
    "![8.test2.png](https://images2018.cnblogs.com/blog/1127869/201809/1127869-20180912093132264-1962087110.png)\n",
    "\n",
    "可以思考一下，为什么`trylock`的时候`p_from.money -= money`和`p_to.money += money`都要放在code最里面\n",
    "\n",
    "参考链接：\n",
    "```\n",
    "守护线程参考：https://www.cnblogs.com/brolanda/p/4709947.html\n",
    "Posix Thread：https://www.cnblogs.com/randyniu/p/9189112.html\n",
    "一句话实现并行：http://chriskiehl.com/article/parallelism-in-one-line\n",
    "进程与线程的一个简单解释：http://www.ruanyifeng.com/blog/2013/04/processes_and_threads.html\n",
    "\n",
    "线程分离方面的参考：\n",
    "http://python.su/forum/topic/20403/\n",
    "https://stackoverflow.com/questions/14175016/python-pthread-detach-analog\n",
    "https://stackoverflow.com/questions/11904848/what-is-the-difference-between-a-detached-thread-and-a-daemon-thread\n",
    "\n",
    "线程锁参考：\n",
    "https://www.cnblogs.com/nuomin/p/7899675.html\n",
    "https://blog.csdn.net/alina_catty/article/details/78792085\n",
    "https://mozillazg.com/2016/09/python-threading-multiprocessing-logging-equal-deadlock.html\n",
    "\n",
    "死锁调试参考：\n",
    "https://blog.alswl.com/2013/11/python-gdb\n",
    "https://wiki.python.org/moin/DebuggingWithGdb\n",
    "http://www.blogjava.net/stone2083/archive/2013/08/19/403028.html\n",
    "https://stackoverflow.com/questions/1289124/python-equivalent-of-jstack\n",
    "https://mozillazg.com/2016/09/python-threading-multiprocessing-logging-equal-deadlock.html\n",
    "https://stackoverflow.com/questions/132058/showing-the-stack-trace-from-a-running-python-application\n",
    "\n",
    "使用ctypes强行杀掉线程：https://blog.csdn.net/vinsuan1993/article/details/78158589\n",
    "老外对杀死子线程的探讨：\n",
    "https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.2.6.线程同步~Queue-引入\n",
    "\n",
    "线程同步这块，之前讲了锁系列，现在把剩下的也说说\n",
    "\n",
    "Queue大家都很熟悉，应用场景很多很多，不仅仅局限在线(进)程同步，很多业务场景都在使用。\n",
    "\n",
    "在开始之前先看一个**秒杀场景**：一般都使用**乐观锁**，也就是大家经常提的**CAS机制**来实现，数据所在的内存值，预期值，新值。当需要更新时，判断当前内存值与之前取到的值是否相等，若相等，则用新值更新，若失败则不断重试（`sleep(random)`）\n",
    "\n",
    "从数据库层面控制就是这样：（原子性操作）\n",
    "```sql\n",
    "update table set amout=amout-#{buys}, version=version+1 where id=#{id} and version=#{version}\n",
    "\n",
    "or\n",
    "\n",
    "update table set amout=amout-#{buys} where id=#{id} and amout-#{buys}>=0\n",
    "```\n",
    "我们用代码模拟一下：(Python里面没有`CountDownLatch`，我们用之前学的条件变量实现一个)\n",
    "```py\n",
    "# 模拟Java里的CountDownLatch（条件变量模拟）\n",
    "# 可以理解为赛跑，当运动员全部准备好了，裁判一枪下去，开始比赛\n",
    "class CountDownLatch(object):\n",
    "    def __init__(self):\n",
    "        self.con = Condition()  # 条件变量\n",
    "\n",
    "    def wait(self):\n",
    "        with self.con:\n",
    "            self.con.wait()\n",
    "\n",
    "    def countDown(self):\n",
    "        with self.con:\n",
    "            self.con.notify_all()  # 开枪（唤醒所有线程）\n",
    "```\n",
    "模拟：\n",
    "```py\n",
    "count = 100  # 库存100件\n",
    "\n",
    "class MyThread(threading.Thread):\n",
    "    def __init__(self, id, con):\n",
    "        self.id = id\n",
    "        self.con = con\n",
    "        super().__init__()\n",
    "\n",
    "    def run(self):\n",
    "        global count\n",
    "        self.con.wait()\n",
    "        if count > 0: # if count - 1 >= 0:\n",
    "            count -= 1\n",
    "            print(f\"线程{self.id}~抢到一件商品\")\n",
    "\n",
    "def main():\n",
    "    con = CountDownLatch()  # 条件变量\n",
    "    t_list = [MyThread(id=i, con=con) for i in range(1000)]\n",
    "    for t in t_list:\n",
    "        t.start()\n",
    "    print(\"准备开抢\")\n",
    "    con.countDown()  # 唤醒所有\n",
    "    for t in t_list:\n",
    "        t.join()\n",
    "    print(f\"剩余库存{count}\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（没错，没用锁一样高并发～）\n",
    "```\n",
    "线程42~抢到一件商品\n",
    "线程49~抢到一件商品\n",
    "线程50~抢到一件商品\n",
    "线程63~抢到一件商品\n",
    "线程84~抢到一件商品\n",
    "线程113~抢到一件商品\n",
    "线程135~抢到一件商品\n",
    "线程161~抢到一件商品\n",
    "线程183~抢到一件商品\n",
    "线程220~抢到一件商品\n",
    "线程271~抢到一件商品\n",
    "线程278~抢到一件商品\n",
    "线程302~抢到一件商品\n",
    "线程359~抢到一件商品\n",
    "线程379~抢到一件商品\n",
    "....\n",
    "线程10~抢到一件商品\n",
    "线程18~抢到一件商品\n",
    "线程23~抢到一件商品\n",
    "线程26~抢到一件商品\n",
    "线程33~抢到一件商品\n",
    "线程44~抢到一件商品\n",
    "线程52~抢到一件商品\n",
    "线程53~抢到一件商品\n",
    "线程158~抢到一件商品\n",
    "线程177~抢到一件商品\n",
    "线程227~抢到一件商品\n",
    "线程289~抢到一件商品\n",
    "线程15~抢到一件商品\n",
    "线程37~抢到一件商品\n",
    "线程134~抢到一件商品\n",
    "线程212~抢到一件商品\n",
    "线程72~抢到一件商品\n",
    "线程305~抢到一件商品\n",
    "线程365~抢到一件商品\n",
    "剩余库存0\n",
    "\n",
    "real\t0m0.189s\n",
    "user\t0m0.161s\n",
    "sys\t0m0.101s\n",
    "\n",
    "```\n",
    "如果你把`if count > 0:`注释掉：（瞬间呵呵哒了）\n",
    "```\n",
    "剩余库存-900\n",
    "\n",
    "real\t0m0.215s\n",
    "user\t0m0.188s\n",
    "sys\t0m0.088s\n",
    "\n",
    "```\n",
    "如果你在修改的时候加个锁：\n",
    "```py\n",
    "real\t0m0.195s\n",
    "user\t0m0.157s\n",
    "sys\t0m0.100s\n",
    "```\n",
    "在这里说，其实没有多大意义，了解下即可（数据库最大连接数是有瓶颈的，后端项目里面一般都是使用缓存的`CAS机制`，比如`Redis`的`watch`、`memcached`的`gets`和`cas`，还有就是我们下面要介绍的`Queue`了）\n",
    "\n",
    "后面会说，引入部分不用深究，记住两个即可：\n",
    "1. 数据库层面的CAS机制（乐观锁）\n",
    "2. Java里面`CountDownLatch`的模拟"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.2.7.线程同步~Queue\n",
    "\n",
    "#### 1.基本使用\n",
    "Queue在讲进程的时候就有说过（进程间通信），线程用法也差不多，看个经典案例：\n",
    "```py\n",
    "import time\n",
    "import random\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Queue\n",
    "\n",
    "def consumer(q, i):\n",
    "    while True:\n",
    "        data = q.get()\n",
    "        print(f\"[消费者{i}]商品{data}抢光了\")\n",
    "\n",
    "def producer(q):\n",
    "    while True:\n",
    "        num = random.random()\n",
    "        q.put(num)\n",
    "        print(f\"[生产者]商品{num}出厂了\\n\")\n",
    "        time.sleep(num)\n",
    "\n",
    "def main():\n",
    "    q = Queue(10)  # 为了演示，我这边限制一下\n",
    "    pool = ThreadPool()\n",
    "    # 一个生产者\n",
    "    pool.apply_async(producer, args=(q,))\n",
    "    # 两个消费者\n",
    "    pool.apply_async(consumer, args=(q, 1))\n",
    "    pool.apply_async(consumer, args=(q, 2))\n",
    "    pool.close()\n",
    "    pool.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出图示：(非阻塞可以使用`put_nowait`和`get_nowait`)\n",
    "![3.queue.gif](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180925111207112-910814594.gif)\n",
    "\n",
    "#### 2.源码探讨\n",
    "\n",
    "Queue是线程安全的放心使用，我们来看看Queue源码：（**条件变量`Condition`和`Lock`的综合使用**）\n",
    "```py\n",
    "class Queue:\n",
    "    def __init__(self, maxsize=0):\n",
    "        self.maxsize = maxsize\n",
    "        self._init(maxsize)\n",
    "        self.mutex = threading.Lock() # 三个Condition公用\n",
    "        \n",
    "        # get的时候使用，如果队列空了就等待\n",
    "        self.not_empty = threading.Condition(self.mutex)\n",
    "        # put的时候使用，如果队列满了就等待\n",
    "        self.not_full = threading.Condition(self.mutex)\n",
    "        # 每当未完成任务的数量降至零时，通知所有线程\n",
    "        self.all_tasks_done = threading.Condition(self.mutex)\n",
    "        \n",
    "        self.unfinished_tasks = 0 # 未完成任务\n",
    "        \n",
    "    def put(self, item, block=True, timeout=None):\n",
    "        # 如果队列满了就等待\n",
    "        # self.not_full = threading.Condition(self.mutex)\n",
    "        with self.not_full:\n",
    "            if self.maxsize > 0:\n",
    "                if not block:\n",
    "                    if self._qsize() >= self.maxsize:\n",
    "                        raise Full\n",
    "                elif timeout is None:\n",
    "                    while self._qsize() >= self.maxsize:\n",
    "                        self.not_full.wait()\n",
    "                elif timeout < 0:\n",
    "                    raise ValueError(\"'timeout' must be a non-negative number\")\n",
    "                else:\n",
    "                    endtime = time() + timeout\n",
    "                    while self._qsize() >= self.maxsize:\n",
    "                        remaining = endtime - time()\n",
    "                        if remaining <= 0.0:\n",
    "                            raise Full\n",
    "                        self.not_full.wait(remaining)\n",
    "            self._put(item)\n",
    "            self.unfinished_tasks += 1\n",
    "            self.not_empty.notify()\n",
    "\n",
    "    def get(self, block=True, timeout=None):\n",
    "        # 如果队列空了就等待\n",
    "        # self.not_empty = threading.Condition(self.mutex)\n",
    "        with self.not_empty:\n",
    "            if not block:\n",
    "                if not self._qsize():\n",
    "                    raise Empty\n",
    "            elif timeout is None:\n",
    "                while not self._qsize():\n",
    "                    self.not_empty.wait()\n",
    "            elif timeout < 0:\n",
    "                raise ValueError(\"'timeout' must be a non-negative number\")\n",
    "            else:\n",
    "                endtime = time() + timeout\n",
    "                while not self._qsize():\n",
    "                    remaining = endtime - time()\n",
    "                    if remaining <= 0.0:\n",
    "                        raise Empty\n",
    "                    self.not_empty.wait(remaining)\n",
    "            item = self._get()\n",
    "            self.not_full.notify()\n",
    "            return item\n",
    "```\n",
    "\n",
    "#### 3.多任务调度\n",
    "\n",
    "来个场景，厂家倒闭（任务列表完成了）怎么通知消费者不用等待了？\n",
    "\n",
    "回顾一下使用协程是怎么解决的：<a href=\"http://www.cnblogs.com/dotnetcrazy/p/9278573.html#5.5.扩展之～协程yield实现多任务调度\" target=\"_blank\">协程yield实现多任务调度</a>\n",
    "```py\n",
    "def consumer():\n",
    "    status = \"\"\n",
    "    while True:\n",
    "        tmp = yield status\n",
    "        if not tmp:\n",
    "            print(\"消费者已经睡觉了...\")\n",
    "            return\n",
    "        print(\"消费者：获得商品%s号...\" % tmp)\n",
    "        status = \"ok\"\n",
    "\n",
    "def produce(c):\n",
    "    # 启动消费者\n",
    "    c.send(None)\n",
    "    for i in range(1, 3):\n",
    "        print(\"生产者：出产商品%s号...\" % i)\n",
    "        # 生产商品，并提交给消费者\n",
    "        status = c.send(i)\n",
    "        print(\"生产者：生产者消费状态: %s\" % status)\n",
    "    # c.send(None) 执行这个会引发StopIteration\n",
    "    c.close()  # 使用close就可以避免了(手动关闭生成器函数，后面的调用会直接返回StopIteration异常)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    # 创建消费者\n",
    "    c = consumer()\n",
    "    produce(c)\n",
    "```\n",
    "输出：\n",
    "```\n",
    "生产者：出产商品1号...\n",
    "消费者：获得商品1号...\n",
    "生产者：生产者消费状态: ok\n",
    "生产者：出产商品2号...\n",
    "消费者：获得商品2号...\n",
    "生产者：生产者消费状态: ok\n",
    "```\n",
    "\n",
    "当使用`Queue`时，协调生产者和消费者的关闭问题可以**在队列中放置一个特殊的值**，当消费者读到这个值的时候，终止执行：\n",
    "```py\n",
    "import time, random, uuid\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Queue\n",
    "\n",
    "stop_obj = uuid.uuid1() # 获取UUID（GUID）\n",
    "\n",
    "def consumer(q, i):\n",
    "    while True:\n",
    "        data = q.get()\n",
    "        if data == stop_obj:\n",
    "            print(f\"[消费者{i}]光荣退伍了\")\n",
    "            q.put(data)  # 如果不加这个，其他消费者就不知道了（Queue里面的数据取出来就没了）\n",
    "            break\n",
    "        print(f\"[消费者{i}]商品{data}抢光了\")\n",
    "\n",
    "def producer(q):\n",
    "    for i in range(10):\n",
    "        num = random.random()\n",
    "        q.put(num)\n",
    "        print(f\"[生产者]商品{num}出厂了\")\n",
    "        time.sleep(num)\n",
    "    q.put(stop_obj)  # 发送结束命令\n",
    "\n",
    "def main():\n",
    "    q = Queue(10)  # 为了演示，我这边限制一下\n",
    "    pool = ThreadPool()\n",
    "    # 一个生产者\n",
    "    pool.apply_async(producer, args=(q,))\n",
    "    # 两个消费者\n",
    "    pool.apply_async(consumer, args=(q, 1))\n",
    "    pool.apply_async(consumer, args=(q, 2))\n",
    "    pool.close()\n",
    "    pool.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "**如果读到特殊值没有再放进队列就不能保证所有消费者都退出任务~Queue里面的数据取出来就没了**\n",
    "输出：（你可以把上面那句注释调看结果）\n",
    "```\n",
    "[生产者]商品0.33594145145041265出厂了\n",
    "[消费者1]商品0.33594145145041265抢光了\n",
    "[生产者]商品0.49907511942411487出厂了\n",
    "[消费者1]商品0.49907511942411487抢光了\n",
    "[生产者]商品0.6875075709064151出厂了\n",
    "[消费者2]商品0.6875075709064151抢光了\n",
    "[生产者]商品0.4039336126048405出厂了\n",
    "[消费者1]商品0.4039336126048405抢光了\n",
    "[生产者]商品0.4339014739644075出厂了\n",
    "[消费者2]商品0.4339014739644075抢光了\n",
    "[生产者]商品0.7101415304586235出厂了\n",
    "[消费者1]商品0.7101415304586235抢光了\n",
    "[生产者]商品0.39303515351899出厂了\n",
    "[消费者2]商品0.39303515351899抢光了\n",
    "[生产者]商品0.07572426360227902出厂了\n",
    "[消费者1]商品0.07572426360227902抢光了\n",
    "[生产者]商品0.8054064710812884出厂了\n",
    "[消费者2]商品0.8054064710812884抢光了\n",
    "[生产者]商品0.8085151230789658出厂了\n",
    "[消费者1]商品0.8085151230789658抢光了\n",
    "[消费者2]光荣退伍了\n",
    "[消费者1]光荣退伍了\n",
    "```\n",
    "在上面案例里面，你把`uuid.uuid1()`换成`object()`，然后比较部分的`==`换成`is`也是可以的，但是分布式系统的话还是使用`UUID`吧\n",
    "\n",
    "#### 4.自定义Queue\n",
    "\n",
    "如果想在`Queue`的基础上**扩展**，可以**自定义数据结构并添加所需的锁和同步机制**（eg:`Condition`）来实现线程间通信(同步)\n",
    "\n",
    "写demo前说说理论：\n",
    "1. 二叉树 ==> 每个节点最多有两个子树的树结构\n",
    "2. 满二叉树 ==> 除了最底层叶结点外，每一个结点都有左右子叶\n",
    "3. 二叉堆 ==> 本质上是一种完全二叉树，它分为两个类型：\n",
    "    1. 最大堆：最大堆任何一个父节点的值，都大于等于它左右子节点的值，**根节点是最大值**\n",
    "    2. 最小堆：最小堆任何一个父节点的值，都小于等于它左右子节点的值，**根节点是最小值**\n",
    "\n",
    "以最小堆为例，画个图演示一下：\n",
    "![3.二叉树.png](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180925175855160-1762123551.png)\n",
    "\n",
    "插入新节点\n",
    "![3.插入新节点.png](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180925175757057-2133843838.png)\n",
    "\n",
    "排序后的二叉树\n",
    "![3.排序.png](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180925180046653-83075187.png)\n",
    "\n",
    "---\n",
    "\n",
    "准备删除节点2\n",
    "![4.删除节点.png](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180925180743440-1671994961.png)\n",
    "\n",
    "把最后一个节点拿过来充数（维护二叉树稳定）\n",
    "![4.最后一个节点.png](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180925180916854-1577983438.png)\n",
    "\n",
    "进行比较排序，把左右节点最小的拉上来\n",
    "![4.比较排序.png](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180925181129791-163322849.png)\n",
    "\n",
    "---\n",
    "\n",
    "**构建二叉堆**：把一个无序的完全二叉树调整为二叉堆（`让所有非叶子节点依次下沉`）\n",
    "\n",
    "来个乱序的二叉树\n",
    "![5.无序二叉树.png](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180925195107449-1387037054.png)\n",
    "\n",
    "从最后一个非叶子节点开始，和最小的子节点交换位置（8和1交换）\n",
    "![5.互换1.png](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180925195225411-1860026119.png)\n",
    "\n",
    "右边的也走一波（6和4交换）\n",
    "![5.互换2.png](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180925195424449-1440927160.png)\n",
    "\n",
    "节点5和1互换\n",
    "![5.互换3.png](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180925195526473-575596034.png)\n",
    "\n",
    "现在根节点最小了（3和1互换）\n",
    "![5互换4.png](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180925195707770-661860846.png)\n",
    "\n",
    "从上往下再排个序，这时候就是最小堆了\n",
    "![5.最小堆.png](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180925195954020-690795564.png)\n",
    "\n",
    "---\n",
    "\n",
    "**看个`完全二叉树`的规律**：若从上至下、从左至右编号，则编号为i的结点：\n",
    "1. 左孩子编号为`2i+1`，其右孩子编号=`2i＋2`\n",
    "2. 父节点编号=`i/2`（根节点没有父节点）\n",
    "\n",
    "把上面二叉树转换成数组：\n",
    "![5.数组.png](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180925203720460-1303543109.png)\n",
    "\n",
    "这时候再去理解优先队列就简单了：\n",
    "1. 最大优先队列，无论入队顺序，当前最大的元素优先出队\n",
    "2. 最小优先队列，无论入队顺序，当前最小的元素优先出队\n",
    "\n",
    "Python提供了一个`heapq`的模块：<a href=\"https://docs.python.org/3/library/heapq.html\" target=\"_blank\">https://docs.python.org/3/library/heapq.html</a>\n",
    "\n",
    "来看个**最小二叉堆**的案例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 2 µs, sys: 0 ns, total: 2 µs\n",
      "Wall time: 5.25 µs\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time\n",
    "\n",
    "import heapq\n",
    "\n",
    "h_list = []\n",
    "# 来个乱序的二叉树（和图示一样）\n",
    "for i in [3, 5, 6, 8, 2, 4, 7, 1, 9]:\n",
    "    heapq.heappush(h_list, i)  # 构建最小二叉堆\n",
    "# 弹出最小值\n",
    "heapq.heappop(h_list) # 查看堆中最小值，不弹出 heap[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 2 µs, sys: 1 µs, total: 3 µs\n",
      "Wall time: 4.77 µs\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(3, '小潘')"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%time\n",
    "\n",
    "import heapq\n",
    "\n",
    "h_list = []\n",
    "# 堆元素可以是元组，可以拓展优先级的概念\n",
    "heapq.heappush(h_list, (9,\"小明\"))\n",
    "heapq.heappush(h_list, (5,\"小张\"))\n",
    "heapq.heappush(h_list, (7,\"小周\"))\n",
    "heapq.heappush(h_list, (3,\"小潘\"))\n",
    "\n",
    "heapq.heappop(h_list)  # 弹出优先级最低的"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "举个使用`Condition`+`二叉堆`实现一个**优先级队列**:\n",
    "```py\n",
    "import heapq\n",
    "from uuid import uuid1\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Condition\n",
    "\n",
    "class MaxPriorityQueue(object):\n",
    "    \"\"\"自定义一个最大优先队列\"\"\"\n",
    "\n",
    "    def __init__(self):\n",
    "        self.__h_list = []\n",
    "        self.__con = Condition()  # 条件变量\n",
    "        self.__index = 0  # 索引\n",
    "\n",
    "    def put(self, value, sort=0):\n",
    "        with self.__con:\n",
    "            # heapq是最小二叉堆，优先级取负就是最大二叉堆了\n",
    "            heapq.heappush(self.__h_list, (-sort, self.__index, value))\n",
    "            self.__index += 1\n",
    "            self.__con.notify()  # 随机通知一个阻塞等的线程\n",
    "\n",
    "    def get(self):\n",
    "        with self.__con:\n",
    "            while 1:\n",
    "                # 0 => False\n",
    "                if not self.qsize():\n",
    "                    self.__con.wait()  # 列表为空则阻塞等\n",
    "                return heapq.heappop(self.__h_list)[-1]  # 返回元组最后一个元素（value）\n",
    "\n",
    "    def qsize(self):\n",
    "        return len(self.__h_list)\n",
    "\n",
    "stop_obj = uuid1()  # 获取UUID（GUID）\n",
    "\n",
    "def task_put(queue):\n",
    "    queue.put(\"小周\", 5)\n",
    "    queue.put(\"小潘\", 7)\n",
    "    queue.put(\"小明\", 3)\n",
    "    queue.put(\"小张\", 9)\n",
    "    global stop_obj\n",
    "    queue.put(stop_obj)\n",
    "\n",
    "def task_get(queue):\n",
    "    global stop_obj\n",
    "    # 全部读出来\n",
    "    while 1:\n",
    "        data = queue.get()\n",
    "        if data == stop_obj:\n",
    "            print(\"光荣退伍了\")\n",
    "            queue.put(stop_obj)  # 保证其他消费者也能安全退出\n",
    "            break\n",
    "        print(data)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    queue = MaxPriorityQueue()\n",
    "    pool = ThreadPool()\n",
    "    pool.apply_async(task_get, args=(queue,))\n",
    "    pool.apply_async(task_put, args=(queue,))\n",
    "    pool.close()\n",
    "    pool.join()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "小张\n",
    "小潘\n",
    "小周\n",
    "小明\n",
    "光荣退伍了\n",
    "```\n",
    "---\n",
    "\n",
    "#### 浅谈`multiprocessing`、`multiprocessing.dummy`、`threading`\n",
    "\n",
    "`multiprocessing.dummy`上面只列举了常用的模块，Queue这块就两个：`Queue`和`JoinableQueue`。既然提到了就顺便说几句，之前写进程篇的时候因为外出，急急忙忙就收尾了，像上面的`Semaphore`和`Condition`以及下面准备说的`Event`和`Barrier`等进程和线程都是通用的\n",
    "\n",
    "如果要是非要找点不同，那么Queue这块还真有点不同，eg：`Queue`里面没有`task_done`和`join`方法，而`JoinableQueue`扩展了，而线程的`Queue`是有`task_done`和`join`的，其他常用的进程api和线程基本上一样，用到的时候查下源码或者看看官方文档即可～\n",
    "\n",
    "进程的`Queue`与`JoinableQueue`：\n",
    "![6.Queue与JoinableQueue.png](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180929120125811-246697202.png)\n",
    "\n",
    "线程的`Queue`：\n",
    "![6.线程的Queue.png](https://img2018.cnblogs.com/blog/1127869/201809/1127869-20180929120755417-1043194569.png)\n",
    "\n",
    "\n",
    "`threading`：\n",
    "```\n",
    "__all__ = [\n",
    "    'get_ident', 'active_count', 'Condition', 'current_thread', 'enumerate',\n",
    "    'main_thread', 'TIMEOUT_MAX', 'Event', 'Lock', 'RLock', 'Semaphore',\n",
    "    'BoundedSemaphore', 'Thread', 'Barrier', 'BrokenBarrierError', 'Timer',\n",
    "    'ThreadError', 'setprofile', 'settrace', 'local', 'stack_size'\n",
    "]\n",
    "```\n",
    "\n",
    "`multiprocessing.dummy`:\n",
    "```\n",
    "__all__ = [\n",
    "    'Process', 'current_process', 'active_children', 'freeze_support',\n",
    "    'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition',\n",
    "    'Event', 'Barrier', 'Queue', 'Manager', 'Pipe', 'Pool', 'JoinableQueue'\n",
    "    ]\n",
    "```\n",
    "\n",
    "`multiprocessing.dummy`可以理解为`multiprocessing`的轻量级并发库：api基本上和`multiprocessing`一致，很多都是在`threading`的基础上修改下或者直接使用（`multiprocessing`在`Process`基础上修改）比如：\n",
    "```py\n",
    "# 被轻量化了，本质还是线程\n",
    "# Process模块：Process = DummyProcess(threading.Thread)\n",
    "\n",
    "# 这就是为什么前面的代码的都是 as ThreadPool，这是怕和Process一起使用的时候把你们带坑里\n",
    "# Pool：multiprocessing.pool.ThreadPool(processes, initializer, initargs)\n",
    "\n",
    "# 为了和进程api使用起来一致\n",
    "# current_process：current_process = threading.current_thread\n",
    "\n",
    "# 再看看导入的模块就知道dummy的本质了：\n",
    "from threading import Lock, RLock, Semaphore, BoundedSemaphore\n",
    "from threading import Event, Condition, Barrier\n",
    "from queue import Queue\n",
    "```\n",
    "\n",
    "#### 5.其他Queue类型（看看就好，完全可以自己封装）\n",
    "\n",
    "##### 1.优先级队列：PriorityQueue\n",
    "\n",
    "看看内部实现：(比我们实现的还精简，秒懂)\n",
    "```py\n",
    "class PriorityQueue(Queue):\n",
    "    '''以优先级顺序检索打开条目的队列的变体（最低的第一个）\n",
    "       item通常是以下形式的元组:(优先级编号，数据）'''\n",
    "    def _init(self, maxsize):\n",
    "        self.queue = []\n",
    "\n",
    "    def _qsize(self):\n",
    "        return len(self.queue)\n",
    "\n",
    "    def _put(self, item):\n",
    "        heapq.heappush(self.queue, item)\n",
    "\n",
    "    def _get(self):\n",
    "        return heapq.heappop(self.queue)\n",
    "```\n",
    "看个上面`MaxPriorityQueue`的案例：（**想要大数字优先级高就变负数**）\n",
    "```py\n",
    "from uuid import uuid1\n",
    "from queue import PriorityQueue\n",
    "from multiprocessing.dummy import Pool as ThreadPool\n",
    "\n",
    "stop_obj = uuid1()  # 获取UUID（GUID）\n",
    "\n",
    "def task_put(queue):\n",
    "    queue.put((-5, \"小周\"))\n",
    "    queue.put((-7, \"小潘\"))\n",
    "    queue.put((-3, \"小明\"))\n",
    "    queue.put((-9, \"小张\"))\n",
    "    global stop_obj\n",
    "    # 可以思考一下为什么用0，如果按照小到大的顺序又该如何设置呢？\n",
    "    queue.put((0, stop_obj))\n",
    "\n",
    "def task_get(queue):\n",
    "    global stop_obj\n",
    "    # 全部读出来\n",
    "    while 1:\n",
    "        data = queue.get()\n",
    "        if data[-1] == stop_obj:\n",
    "            print(\"光荣退伍了\")\n",
    "            queue.put((0, stop_obj))  # 保证其他消费者也能安全退出\n",
    "            break\n",
    "        print(data[-1])\n",
    "\n",
    "def error_print(msg):\n",
    "    print(msg)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    queue = PriorityQueue()\n",
    "    pool = ThreadPool()\n",
    "    pool.apply_async(task_get, args=(queue, ), error_callback=error_print)\n",
    "    pool.apply_async(task_put, args=(queue, ), error_callback=error_print)\n",
    "    pool.close()\n",
    "    pool.join()\n",
    "```\n",
    "输出：（如果功能不够用还是自己设计吧，**设计的太简单调用的时候会比较麻烦**）\n",
    "```\n",
    "小张\n",
    "小潘\n",
    "小周\n",
    "小明\n",
    "光荣退伍了\n",
    "```\n",
    "\n",
    "##### 2.后进先出队列：LifoQueue\n",
    "\n",
    "一看好像很高大上，翻翻源码：（其实就是基于List封装了个类，看来`multiprocessing.dummy`重写这个是有原因的）\n",
    "```py\n",
    "class LifoQueue(Queue):\n",
    "    def _init(self, maxsize):\n",
    "        self.queue = []\n",
    "\n",
    "    def _qsize(self):\n",
    "        return len(self.queue)\n",
    "\n",
    "    def _put(self, item):\n",
    "        self.queue.append(item)\n",
    "\n",
    "    def _get(self):\n",
    "        return self.queue.pop()\n",
    "```\n",
    "看个使用案例：（完全可以直接使用List...）\n",
    "```py\n",
    "from queue import LifoQueue\n",
    "\n",
    "def main():\n",
    "    queue = LifoQueue()\n",
    "\n",
    "    for i in range(10):\n",
    "        queue.put(i)\n",
    "\n",
    "    for i in range(queue.qsize()):\n",
    "        print(queue.get())\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "9\n",
    "8\n",
    "7\n",
    "6\n",
    "5\n",
    "4\n",
    "3\n",
    "2\n",
    "1\n",
    "0\n",
    "```\n",
    "\n",
    "##### other\n",
    "\n",
    "**`SimpleQueue`** 就不说了，和Queue使用基本上一样。线程和进程有点不一样，注意下：（`进程间通信手段毕竟比线程少`）\n",
    "1. `threading`中的`SimpleQueue`是`FIFO`简单队列\n",
    "2. `multiprocessing`中的`SimpleQueue`是在`PIPE`管道的基础上封装版\n",
    "\n",
    "**`JoinableQueue`** 在`multiprocessing.dummy`就是`Queue`：(等会直接使用`Queue`即可)\n",
    "```py\n",
    "# multiprocessing/dummy/__init__.py\n",
    "from queue import Queue\n",
    "JoinableQueue = Queue\n",
    "```\n",
    "相关源码：（下面会和`Queue`对比举例）\n",
    "```py\n",
    "class Queue:\n",
    "    def __init__(self, maxsize=0):\n",
    "        self.maxsize = maxsize\n",
    "        self._init(maxsize)\n",
    "        self.mutex = threading.Lock()\n",
    "        self.not_empty = threading.Condition(self.mutex)\n",
    "        self.not_full = threading.Condition(self.mutex)\n",
    "        self.all_tasks_done = threading.Condition(self.mutex)\n",
    "        # 进程在这边使用的是Semaphore\n",
    "        self.unfinished_tasks = 0\n",
    "\n",
    "    def task_done(self):\n",
    "        with self.all_tasks_done:\n",
    "            unfinished = self.unfinished_tasks - 1\n",
    "            if unfinished <= 0:\n",
    "                if unfinished < 0:\n",
    "                    raise ValueError('task_done() called too many times')\n",
    "                self.all_tasks_done.notify_all()\n",
    "            self.unfinished_tasks = unfinished\n",
    "\n",
    "    def join(self):\n",
    "        with self.all_tasks_done:\n",
    "            while self.unfinished_tasks:\n",
    "                self.all_tasks_done.wait()\n",
    "```\n",
    "\n",
    "在`multiprocessing`中的`Queue`没有`task_done`和`join`方法，所以有了`JoinableQueue`：\n",
    "```py\n",
    "# multiprocessing/queues.py\n",
    "\n",
    "class JoinableQueue(Queue):\n",
    "    def __init__(self, maxsize=0, *, ctx):\n",
    "        Queue.__init__(self, maxsize, ctx=ctx)\n",
    "        self._unfinished_tasks = ctx.Semaphore(0)\n",
    "        self._cond = ctx.Condition()\n",
    "\n",
    "    def task_done(self):\n",
    "        with self._cond:\n",
    "            if not self._unfinished_tasks.acquire(False):\n",
    "                raise ValueError('task_done() called too many times')\n",
    "            if self._unfinished_tasks._semlock._is_zero():\n",
    "                self._cond.notify_all()\n",
    "\n",
    "    def join(self):\n",
    "        with self._cond:\n",
    "            if not self._unfinished_tasks._semlock._is_zero():\n",
    "                self._cond.wait()\n",
    "```\n",
    "\n",
    "#### 6.Queue拓展\n",
    "\n",
    "使用队列来进行线程间通信是一个单向、不确定的过程。通常情况下，没法知道接收数据的线程是什么时候接收到数据并开始工作的。这时候就可以使用`Queue`提供的`task_done()`和`join()`了～\n",
    "\n",
    "**之前通知消费者退出是使用发一个消息的方式，这次换种思路～直接设置后台线(进)程，然后使用`Queue`的`join`方法**：\n",
    "```py\n",
    "from multiprocessing.dummy import threading, Queue\n",
    "\n",
    "def consumer(queue):\n",
    "    while 1:\n",
    "        data = queue.get()\n",
    "        print(f\"[消费者]消费商品{data}号\")\n",
    "        # 通知Queue完成任务了\n",
    "        queue.task_done()\n",
    "\n",
    "def producer(queue):\n",
    "    for i in range(10):\n",
    "        print(f\"[生产者]生产商品{i}号\")\n",
    "        queue.put(i)\n",
    "\n",
    "def main():\n",
    "    queue = Queue()\n",
    "    # 开启生产消费者线程任务\n",
    "    t_list = [\n",
    "        threading.Thread(target=func, args=(queue, ))\n",
    "        for func in (producer, consumer)\n",
    "    ]\n",
    "    # 启动两个线程\n",
    "    for t in t_list:\n",
    "        # 设置后台线程，就算是死循环当主线程退出的时候也会退出的\n",
    "        t.setDaemon(True)  # 进程是daemon属性，t.daemon=True\n",
    "        t.start()\n",
    "    # 等待所有任务完成\n",
    "    queue.join()  # 你可以把这句话注释掉看输出\n",
    "    print(f\"当前队列未完成的数量：{queue.unfinished_tasks}\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "[生产者]生产商品0号\n",
    "[生产者]生产商品1号\n",
    "[消费者]消费商品0号\n",
    "[生产者]生产商品2号\n",
    "[消费者]消费商品1号\n",
    "[生产者]生产商品3号\n",
    "[消费者]消费商品2号\n",
    "[生产者]生产商品4号\n",
    "[消费者]消费商品3号\n",
    "[生产者]生产商品5号\n",
    "[消费者]消费商品4号\n",
    "[生产者]生产商品6号\n",
    "[消费者]消费商品5号\n",
    "[生产者]生产商品7号\n",
    "[消费者]消费商品6号\n",
    "[生产者]生产商品8号\n",
    "[消费者]消费商品7号\n",
    "[生产者]生产商品9号\n",
    "[消费者]消费商品8号\n",
    "[消费者]消费商品9号\n",
    "当前队列未完成的数量：0\n",
    "```\n",
    "进程案例见：<a href=\"https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Thread/2.lock_queue/3.queue/6.JoinableQueue.py\" target=\"_blank\">/BaseCode/tree/master/python5.concurrent/Thread/2.lock_queue/3.queue/6.JoinableQueue.py</a>\n",
    "\n",
    "PS：其实Queue的完整写法应该是每次收到消息的时候调用一下`q.task_done()`，便于记录未完成状态，大家进程的`Queue`用多了，也就不太写了。现在`task_done`讲过了，以后用线程的`Queue`和进程的`JoinableQueue`记得加上哦～\n",
    "\n",
    "再扩展一下，看看`queue.join`源码：（**如果还不清楚，下面还有一个手写线程池的demo**）\n",
    "```py\n",
    "def join(self):\n",
    "    # Condition条件变量\n",
    "    with self.all_tasks_done:\n",
    "        # 如果还有没有完成的任务就调用Condition的wait()方法\n",
    "        while self.unfinished_tasks:\n",
    "            self.all_tasks_done.wait()\n",
    "```\n",
    "\n",
    "Queue对象的方法：\n",
    "1. `q.full()`：判断队列是否已满\n",
    "2. `q.empty()`：判断队列是否为空\n",
    "3. `q.qsize()`：返回当前队列中的元素个数\n",
    "4. `q.get_nowait()`：非阻塞获取消息，等价于`q.get(block=Flase)`\n",
    "5. `q.put_nowait()`：非阻塞发送消息，等价于`q.put(block=Flase)`\n",
    "6. `q.join()`：等待所有任务完成\n",
    "7. `q.task_done()`：在Queue中标记任务完成\n",
    "\n",
    "PS：`q.qsize()`、`q.full()`、`q.empty()`等方法可以获取一个队列的当前大小和状态。但要注意，这些方法都**不是线程安全的**。\n",
    "\n",
    "可能你对一个队列使用`empty()`判断出这个队列为空，但同时另外一个线程可能已经向这个队列中插入一个数据项。所以，你最好不要在你的代码中使用这些方法。\n",
    "\n",
    "queue模块定义的异常类：\n",
    "1. `queue.Full`：非阻塞发送消息时，如果队列满了～抛异常\n",
    "2. `queue.Empty`：非阻塞获取消息时，如果队列为空～抛异常\n",
    "\n",
    "eg:\n",
    "```py\n",
    "try:\n",
    "    data = q.get_nowait() # get(timeout=5)\n",
    "except queue.Empty:\n",
    "    pass\n",
    "```\n",
    "\n",
    "基于简单队列编写多线程程序在线程安全队列的底层实现来看，你无需在你的代码中使用锁和其他底层的同步机制，使用队列这种基于消息的通信机制可以被扩展到更大的应用范畴，比如，你可以把你的程序放入多个进程甚至是分布式系统而无需改变底层的队列结构。\n",
    "\n",
    "使用线程队列有一个要注意的问题：**向队列中添加数据项时并不会复制此数据项，线程间通信实际上是在线程间传递对象引用。如果担心对象的共享状态，那最好只传递不可修改的数据结构**（如：整型、字符串或者元组）**或者一个对象的深拷贝**`copy.deepcopy(data)`\n",
    "\n",
    "#### 7.使用Queue实现一个线程池\n",
    "\n",
    "和网络整合版的线程池后面再说，`ThreadPoolExecutor`深入篇后会说，先模仿官方`Pool`来个精简版：\n",
    "```py\n",
    "from multiprocessing.dummy import threading, Queue\n",
    "\n",
    "class Task(threading.Thread):\n",
    "    def __init__(self, queue):\n",
    "        super().__init__()\n",
    "        self.queue = queue\n",
    "\n",
    "        self.setDaemon(True)  # 设置后台线程，主线程结束就终止\n",
    "        self.start()  # 开启线程，执行run方法\n",
    "        print(f\"开启一个线程～{self.name}\")\n",
    "\n",
    "    def run(self):\n",
    "        func, args, kws = self.queue.get()\n",
    "        try:\n",
    "            func(args, kws)\n",
    "        except Exception as ex:\n",
    "            print(ex)\n",
    "        finally:\n",
    "            self.queue.task_done()\n",
    "\n",
    "class ThreadPool(object):\n",
    "    def __init__(self, count=0):\n",
    "        # 设置Pool运行状态\n",
    "        self.running = True\n",
    "\n",
    "        from os import cpu_count  # 用到的时候导入对应模块即可\n",
    "        # 默认是CPU核数，且至少有一个线程\n",
    "        if count <= 0:\n",
    "            count = cpu_count() or 1\n",
    "        # 设置线程数\n",
    "        self.queue = Queue(count)\n",
    "\n",
    "        # 启动对应个数的线程\n",
    "        for _ in range(count):\n",
    "            Task(self.queue)  # 不能在这直接启动，会阻塞Pool的\n",
    "\n",
    "    def apply_async(self, func, args=(), kws={}):\n",
    "        if self.running:\n",
    "            # 执行任务\n",
    "            self.queue.put((func, args, kws))\n",
    "\n",
    "    def close(self):\n",
    "        # 不再运行加入任务\n",
    "        self.running = False\n",
    "\n",
    "    def join(self):\n",
    "        # 等待任务执行完退出\n",
    "        self.queue.join()\n",
    "```\n",
    "调用和官方风格一致：\n",
    "```py\n",
    "def call_dad(*args, **kws):\n",
    "    from time import sleep\n",
    "    from random import randint\n",
    "    n = randint(1, 2) # [1,2]\n",
    "    print(f\"休息{n}s\")\n",
    "    sleep(n)\n",
    "    print(f\"{args}~{kws}\")\n",
    "\n",
    "def main():\n",
    "    pool = ThreadPool()\n",
    "    pool.apply_async(call_dad, args=(1, 2, 3), kws={\"dad\": \"小明\"})\n",
    "    pool.apply_async(call_dad, args=(1, 2, 3), kws={\"dad\": \"小张\"})\n",
    "    pool.close()\n",
    "    pool.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（有些偶尔用的模块可以用的时候再导入【别放循环里，虽然重复导入模块不怎么耗时，但是总归有损耗的】）\n",
    "```\n",
    "开启一个线程～Thread-1\n",
    "开启一个线程～Thread-2\n",
    "开启一个线程～Thread-3\n",
    "开启一个线程～Thread-4\n",
    "休息1s\n",
    "休息2s\n",
    "((1, 2, 3), {'dad': '小明'})~{}\n",
    "((1, 2, 3), {'dad': '小张'})~{}\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.2.8.线程同步~Event\n",
    "\n",
    "#### 1.初识\n",
    "\n",
    "线程的一个关键特性是每个线程都是独立运行且状态不可预测。如果程序中的其他线程需要通过判断某个线程的状态来确定自己下一步的操作,这时线程同步问题就比较麻烦。这时候我们就可以使用`Event`了～eg：(类比JQ里面的事件～eg：单击事件)\n",
    "\n",
    "```py\n",
    "from time import sleep\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Event\n",
    "\n",
    "event = Event()\n",
    "\n",
    "def click():\n",
    "    # event.clear()  # 设置标准为假（默认是False）\n",
    "    print(\"用户在修改网页表单\")\n",
    "    sleep(2)\n",
    "    print(\"点击了修改案例\")\n",
    "    event.set()  # 设置标准为真\n",
    "\n",
    "def update():\n",
    "    print(f\"事件状态：{event.is_set()}\")\n",
    "    event.wait()  # 等待到标志为真\n",
    "    print(\"修改成功\")\n",
    "    print(f\"事件状态：{event.is_set()}\")\n",
    "\n",
    "def main():\n",
    "    pool = ThreadPool()\n",
    "    pool.apply_async(click)\n",
    "    pool.apply_async(update)\n",
    "    pool.apply_async(click)\n",
    "    pool.close()\n",
    "    pool.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "用户在修改网页表单\n",
    "事件状态：False\n",
    "用户在修改网页表单\n",
    "点击了修改案例\n",
    "点击了修改案例\n",
    "修改成功\n",
    "事件状态：True\n",
    "```\n",
    "\n",
    "常用方法：\n",
    "1. `event.clear()`：**恢复event的状态值为False**（并发场景下有大用）\n",
    "2. `event.wait()`：如果`event.is_set()==False`将阻塞线程\n",
    "3. `event.set()`： 设置`event`的状态值为`True`，所有阻塞池的线程激活进入就绪状态， 等待操作系统调度\n",
    "4. `event.is_set()`：返回`event`的状态值（**如果想非阻塞等可以使用这个先判断**）线程有个重命名的方法叫`isSet`。PS：进程线程中都有`is_set`方法\n",
    "\n",
    "#### 2.案例\n",
    "\n",
    "`Event`对象包含一个可由线程设置的信号标志,它允许线程等待某些事件的发生：\n",
    "1. 在初始情况下,`Event`对象中的信号标志被设置为假。等待`Event`对象的线程将会被一直阻塞至标志为真。\n",
    "2. 当一个线程将一个`Event`对象的信号标志设置为真,它将唤醒所有等待这个`Event`对象的线程。等待`Event`的线程将忽略这个事件, 继续执行\n",
    "\n",
    "再来个简单版的生产消费者的案例：\n",
    "```py\n",
    "from time import sleep\n",
    "from random import random\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Event\n",
    "\n",
    "global_list = []\n",
    "event = Event()\n",
    "stop_event = Event()\n",
    "\n",
    "n = 0\n",
    "\n",
    "def consumer(i):\n",
    "    print(f\"消费者{i}等待ing\")\n",
    "    while 1:\n",
    "        event.wait()\n",
    "        count = len(global_list)\n",
    "        # 防止List空的时候pop出错\n",
    "        if count > 0:\n",
    "            print(f\"消费了产品{global_list.pop()}\")\n",
    "            # 重置状态（加这一句能减少很多次循环）\n",
    "            event.clear()  # 可以思考一下为什么（提示：Lock）\n",
    "        # 防止生产者结束了，但是消费者还没处理完成\n",
    "        elif len(global_list) == 0 and stop_event.is_set():\n",
    "            break\n",
    "        global n\n",
    "        n += 1\n",
    "    print(f\"消费者{i}完成任务～总共循环{n}次\")\n",
    "\n",
    "def producer():\n",
    "    print(\"生产者正在生产商品\")\n",
    "    for i in range(10):\n",
    "        global_list.append(i)\n",
    "        sleep(random())  # 模拟网络延迟\n",
    "        event.set()  # 通知消费者生产结束\n",
    "    stop_event.set()  # 通知消费者已经可以结束线程了\n",
    "\n",
    "def main():\n",
    "    pool = ThreadPool()\n",
    "    pool.map_async(consumer, range(2))  # 两个消费者\n",
    "    pool.apply_async(producer)  #\n",
    "    pool.close()\n",
    "    pool.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（是不是又感觉多了种**消费者安全退出**的方式？）\n",
    "```\n",
    "消费者0等待ing\n",
    "消费者1等待ing\n",
    "生产者正在生产商品\n",
    "消费了产品1\n",
    "消费了产品0\n",
    "消费了产品2\n",
    "消费了产品3\n",
    "消费了产品4\n",
    "消费了产品5\n",
    "消费了产品6\n",
    "消费了产品7\n",
    "消费了产品8\n",
    "消费了产品9\n",
    "消费者0完成任务\n",
    "消费者1完成任务\n",
    "```\n",
    "PS：while条件换成：`while not (len(global_list) == 0 and stop_event.is_set()):`也行\n",
    "\n",
    "**如果一个线程需要在一个“消费者”线程处理完特定的数据项时立即得到通知，你可以把要发送的数据和一个`Event`一起使用，这样“生产者”就可以通过这个`Event`对象来监测处理的过程了**\n",
    "```py\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Queue, Event\n",
    "\n",
    "def producer(queue):\n",
    "    for i in range(10):\n",
    "        event = Event()\n",
    "        queue.put((event, i))\n",
    "        print(f\"[生产者]生产了产品{i}\")\n",
    "        event.wait()  # 等待消费者通知\n",
    "        print(f\"生产者已经收到消费情况的反馈{i}\")\n",
    "\n",
    "def consumer(queue):\n",
    "    while True:\n",
    "        evt, data = queue.get()\n",
    "        print(f\"[消费者]消费了产品{data}\")\n",
    "        evt.set()  # 通知生产者\n",
    "\n",
    "def main():\n",
    "    queue = Queue()\n",
    "    pool = ThreadPool()\n",
    "    pool.apply_async(consumer, args=(queue, ))\n",
    "    pool.apply_async(producer, args=(queue, ))\n",
    "    pool.close()\n",
    "    pool.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（进程只需微微改动即可使用）\n",
    "```\n",
    "[生产者]生产了产品0\n",
    "[消费者]消费了产品0\n",
    "生产者已经收到消费情况的反馈0\n",
    "[生产者]生产了产品1\n",
    "[消费者]消费了产品1\n",
    "生产者已经收到消费情况的反馈1\n",
    "[生产者]生产了产品2\n",
    "[消费者]消费了产品2\n",
    "生产者已经收到消费情况的反馈2\n",
    "[生产者]生产了产品3\n",
    "[消费者]消费了产品3\n",
    "生产者已经收到消费情况的反馈3\n",
    "[生产者]生产了产品4\n",
    "[消费者]消费了产品4\n",
    "生产者已经收到消费情况的反馈4\n",
    "[生产者]生产了产品5\n",
    "[消费者]消费了产品5\n",
    "生产者已经收到消费情况的反馈5\n",
    "[生产者]生产了产品6\n",
    "[消费者]消费了产品6\n",
    "生产者已经收到消费情况的反馈6\n",
    "[生产者]生产了产品7\n",
    "[消费者]消费了产品7\n",
    "生产者已经收到消费情况的反馈7\n",
    "[生产者]生产了产品8\n",
    "[消费者]消费了产品8\n",
    "生产者已经收到消费情况的反馈8\n",
    "[生产者]生产了产品9\n",
    "[消费者]消费了产品9\n",
    "生产者已经收到消费情况的反馈9\n",
    "```\n",
    "\n",
    "#### 3.本质\n",
    "\n",
    "来看看`Event`到底是何方神圣：（**本质就是基于`Condition`封装了一个标识位，来标记事件是否完成**）\n",
    "```py\n",
    "class Event:\n",
    "    def __init__(self):\n",
    "        self._cond = Condition(Lock()) # 条件变量\n",
    "        self._flag = False\n",
    "\n",
    "    def is_set(self):\n",
    "        return self._flag\n",
    "\n",
    "    isSet = is_set # 建议用is_set，这样进程和线程方法就一致了\n",
    "\n",
    "    def set(self):\n",
    "        with self._cond:\n",
    "            self._flag = True\n",
    "            self._cond.notify_all()\n",
    "\n",
    "    def clear(self):\n",
    "        with self._cond:\n",
    "            self._flag = False\n",
    "\n",
    "    def wait(self, timeout=None):\n",
    "        with self._cond:\n",
    "            signaled = self._flag\n",
    "            if not signaled:\n",
    "                signaled = self._cond.wait(timeout)\n",
    "            return signaled\n",
    "```\n",
    "其实应用场景很多，用起来比`Condition`方便，比如**在连接远程数据库或者访问api的时候设置一个重试机制，成功后再执行SQL或者数据处理**：\n",
    "```py\n",
    "from time import sleep\n",
    "from multiprocessing.dummy import Pool as ThreadPool, Event\n",
    "\n",
    "event = Event()\n",
    "\n",
    "def conn_redis():\n",
    "    n = 1\n",
    "    time_out = 0.5\n",
    "    # 重试机制\n",
    "    while not event.is_set():\n",
    "        if n == 4:  # 自定义重试次数\n",
    "            raise TimeoutError(\"\\033[41mRedis连接超时，请重试\\033[0m\")\n",
    "        event.wait(time_out * n)  # 公共组件，设置超时机制\n",
    "        print(f\"[第{n}次尝试]Redis当前连接超时，正在重试～\")\n",
    "        n += 1\n",
    "    print(\"\\033[42mRedis连接成功\\033[0m\")\n",
    "\n",
    "def update_config():\n",
    "    print(\"正在配置中心获取最新配置～\")\n",
    "    sleep(3)  # 模拟网络延迟\n",
    "    event.set()  # 同步后标记一下\n",
    "\n",
    "def error_callback(data):\n",
    "    print(data)\n",
    "\n",
    "def main():\n",
    "    pool = ThreadPool()\n",
    "    pool.apply_async(update_config, error_callback=error_callback)\n",
    "    pool.apply_async(conn_redis, error_callback=error_callback)\n",
    "    pool.close()\n",
    "    pool.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "动态输出：\n",
    "![7.event.gif](https://img2018.cnblogs.com/blog/1127869/201810/1127869-20181003170402284-1995184115.gif)\n",
    "\n",
    "---\n",
    "\n",
    "##### 回调函数的回顾\n",
    "\n",
    "利用`Pool`提供的`callback`和`error_callback`：\n",
    "```py\n",
    "from time import sleep\n",
    "from multiprocessing.dummy import Pool as ThreadPool\n",
    "\n",
    "def get_data(id):\n",
    "    print(f\"正在请求API，ID={id}\")\n",
    "    sleep(1)\n",
    "    return f\"{id}-Data\"\n",
    "\n",
    "def save_data(data):\n",
    "    sleep(1)\n",
    "    print(f\"保存数据：{data}\")\n",
    "\n",
    "def main():\n",
    "    pool = ThreadPool()\n",
    "    # 每一个执行完毕后处理\n",
    "    for i in range(10):\n",
    "        pool.apply_async(get_data, args=(i, ), callback=save_data)\n",
    "    pool.close()\n",
    "    pool.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "正在请求API，ID=0\n",
    "正在请求API，ID=1\n",
    "正在请求API，ID=3\n",
    "正在请求API，ID=2\n",
    "正在请求API，ID=4\n",
    "保存数据：3-Data\n",
    "正在请求API，ID=5\n",
    "保存数据：4-Data\n",
    "正在请求API，ID=6\n",
    "保存数据：5-Data\n",
    "正在请求API，ID=7\n",
    "保存数据：1-Data\n",
    "正在请求API，ID=8\n",
    "保存数据：7-Data\n",
    "正在请求API，ID=9\n",
    "保存数据：6-Data\n",
    "保存数据：8-Data\n",
    "保存数据：0-Data\n",
    "保存数据：2-Data\n",
    "保存数据：9-Dat\n",
    "\n",
    "real    0m11.096s\n",
    "user    0m0.075s\n",
    "sys     0m0.013s\n",
    "```\n",
    "\n",
    "如果想要简单的并行并且返回结果统一处理，可以把：\n",
    "```py\n",
    "# 每一个执行完毕后执行save_data\n",
    "for i in range(10):\n",
    "    pool.apply_async(get_data, args=(i, ), callback=save_data)\n",
    "```\n",
    "换成：\n",
    "```py\n",
    "# 全部执行完毕后执行save_data\n",
    "pool.map_async(get_data, range(10), callback=save_data)\n",
    "```\n",
    "输出：（**联想一条条插入数据和批量插入数据**）\n",
    "```\n",
    "正在请求API，ID=0\n",
    "正在请求API，ID=1\n",
    "正在请求API，ID=2\n",
    "正在请求API，ID=3\n",
    "正在请求API，ID=4\n",
    "正在请求API，ID=5\n",
    "正在请求API，ID=7\n",
    "正在请求API，ID=6\n",
    "正在请求API，ID=8\n",
    "正在请求API，ID=9\n",
    "保存数据：['0-Data', '1-Data', '2-Data', '3-Data', '4-Data', '5-Data', '6-Data', '7-Data', '8-Data', '9-Data']\n",
    "\n",
    "real    0m4.069s\n",
    "user    0m0.061s\n",
    "sys     0m0.009s\n",
    "```\n",
    "\n",
    "### 扩展：timer\n",
    "\n",
    "先看一个简单案例：\n",
    "```py\n",
    "from time import sleep\n",
    "from threading import Timer\n",
    "\n",
    "def test(obj):\n",
    "    print(f\"timer开始执行~ {obj}\")\n",
    "    sleep(1)\n",
    "    print(f\"timer执行完毕~ {obj}\")\n",
    "\n",
    "def main():\n",
    "    t = Timer(2, test, args=(\"mmd\", ))\n",
    "    t.start()\n",
    "    # t.join()  # 加这句，主线程就会等待timer执行完毕后退出\n",
    "    # t.cancel()  # 停止timer\n",
    "    print(\"主线程over\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "主线程over\n",
    "timer开始执行~ mmd\n",
    "timer执行完毕~ mmd\n",
    "\n",
    "real    0m3.063s\n",
    "user    0m0.043s\n",
    "sys     0m0.004s\n",
    "```\n",
    "运行图示：\n",
    "![7.timer.png](https://img2018.cnblogs.com/blog/1127869/201810/1127869-20181005133742850-1489368778.png)\n",
    "\n",
    "咱们看看源码是怎么回事：\n",
    "```py\n",
    "class Timer(Thread):\n",
    "    def __init__(self, interval, function, args=None, kwargs=None):\n",
    "        Thread.__init__(self)\n",
    "        self.interval = interval\n",
    "        self.function = function\n",
    "        self.args = args if args is not None else []\n",
    "        self.kwargs = kwargs if kwargs is not None else {}\n",
    "        self.finished = Event() # 事件标记\n",
    "\n",
    "    def cancel(self):\n",
    "        self.finished.set() # 事件标记为True（is_set）\n",
    "\n",
    "    def run(self):\n",
    "        self.finished.wait(self.interval) # 限时等\n",
    "        # 没有被取消就执行方法\n",
    "        if not self.finished.is_set():\n",
    "            self.function(*self.args, **self.kwargs)\n",
    "        self.finished.set() # 完成标记\n",
    "```\n",
    "**原来`timer`是在线程的基础上封装了一下。利用`Event`来标记`完成/取消`与否**，与之前讲的定时器不太一样（点我回顾：<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9363810.html#2.4.6.进程间通信～Signal信号\" target=\"_blank\">Signal信号</a>）\n",
    "\n",
    "Timer类是Thread的子类。Timers和线程的启动方式一样，调用其start()方法。timer可以在动作执行前调用其cancel()取消其执行。imer有点像定时器，启动一个线程，定时执行某个任务。**此外，Timer还可以处理各种超时情况～比如终结subprocess创建的进程(`p.kill()`)**\n",
    "\n",
    "再来个定时执行的案例：\n",
    "```py\n",
    "from threading import Timer\n",
    "\n",
    "\n",
    "def test(name):\n",
    "    print(f\"我是牛逼牛逼哄哄的~{name}\")\n",
    "    timer = Timer(2, test, args=(\"小明\",))\n",
    "    timer.start()\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    t = Timer(2, test, (\"小明\",))  # Thread(target=test, args=(\"小明\",))\n",
    "    t.start()\n",
    "```\n",
    "输出：（可以思考比死循环好在哪？提示：`wait`）\n",
    "```\n",
    "我是牛逼牛逼哄哄的~小明\n",
    "我是牛逼牛逼哄哄的~小明\n",
    "我是牛逼牛逼哄哄的~小明\n",
    "我是牛逼牛逼哄哄的~小明\n",
    "我是牛逼牛逼哄哄的~小明\n",
    "........\n",
    "```\n",
    "\n",
    "### 2.2.9.线程同步~Barrier\n",
    "\n",
    "官方文档：`https://docs.python.org/3/library/threading.html#barrier-objects`\n",
    "\n",
    "提供了一个简单的同步原语(机制)，供需要相互等待的固定数量的线程使用。每个线程都试图通过调用`wait()`方法来传递屏障，并将阻塞直到所有线程都进行了`wait()`调用。此时，线程同时释放。\n",
    "\n",
    "看一个官方案例：（**同步客户端和服务器线程**）\n",
    "```py\n",
    "b = Barrier(2, timeout=5)\n",
    "\n",
    "def server():\n",
    "    start_server()\n",
    "    b.wait()\n",
    "    while True:\n",
    "        connection = accept_connection()\n",
    "        process_server_connection(connection)\n",
    "\n",
    "def client():\n",
    "    b.wait()\n",
    "    while True:\n",
    "        connection = make_connection()\n",
    "        process_client_connection(connection)\n",
    "```\n",
    "\n",
    "说到这个不得不提一下我们`Queue`引入篇自己模拟的`伪CountDownLatch`，两者异同之处不少，下面贴了参考链接可以课外拓展一下，大体区别是一个是等待线程组且不可重用，另一个是等待多个线程且可重用(`Barrier`)。**有点像跑步比赛，大家都准备好（全都调用了`wait`），才允许一起跑（执行）**【区别无非是一组起跑还是多组起跑】\n",
    "\n",
    "很显然，上面那个模拟并发的例子使用`Barrier`更简单和应景（也是基于`Condition`封装的，比我们封装的更完美）\n",
    "```py\n",
    "from multiprocessing.dummy import threading\n",
    "\n",
    "count = 100  # 库存100件\n",
    "bar = threading.Barrier(1000, timeout=5)\n",
    "\n",
    "def shopping(id):\n",
    "    global count, bar\n",
    "    try:\n",
    "        bar.wait()  # Barrier wait\n",
    "    except threading.BrokenBarrierError as ex:\n",
    "        print(ex)\n",
    "    except Exception as ex:\n",
    "        print(ex)\n",
    "    # 乐观锁\n",
    "    if count > 0:  # if count - 1 >= 0:\n",
    "        count -= 1\n",
    "        print(f\"线程{id}~抢到一件商品\\n\")\n",
    "\n",
    "def main():\n",
    "    t_list = [threading.Thread(target=shopping, args=(i,)) for i in range(1000)]\n",
    "    print(\"准备开抢ing\")\n",
    "    for t in t_list:\n",
    "        t.start()\n",
    "    for t in t_list:\n",
    "        t.join()\n",
    "    print(f\"剩余库存{count}\")\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：(如果使用`Pool`，记得指定线程数，不然就给自己挖坑了)\n",
    "```\n",
    "准备开抢ing\n",
    "线程999~抢到一件商品\n",
    "线程0~抢到一件商品\n",
    "线程2~抢到一件商品\n",
    "线程6~抢到一件商品\n",
    "线程9~抢到一件商品\n",
    "线程12~抢到一件商品\n",
    "线程13~抢到一件商品\n",
    "线程15~抢到一件商品\n",
    "线程18~抢到一件商品\n",
    "线程21~抢到一件商品\n",
    ".........\n",
    "线程399~抢到一件商品\n",
    "线程408~抢到一件商品\n",
    "线程318~抢到一件商品\n",
    "线程396~抢到一件商品\n",
    "线程432~抢到一件商品\n",
    "\n",
    "剩余库存0\n",
    "\n",
    "real    0m0.531s\n",
    "user    0m0.191s\n",
    "sys     0m0.125s\n",
    "```\n",
    "\n",
    "`class threading.Barrier(parties, action=None, timeout=None)`\n",
    "1. `parties`指定需要等待的线程数\n",
    "2. `action`是一个可调用的，当它被提供时，它们将在它们全部进入屏障之后并且在释放所有线程之前由其中一个线程调用。\n",
    "3. 如果提供`timeout`，则将其用作所有后续`wait()`调用的默认值\n",
    "\n",
    "常见方法：\n",
    "1. `bar.parties`：同步的线程数\n",
    "2. `bar.wait(timeout=None)` 等待线程大部队到齐\n",
    "3. `bar.reset()`：重置Barrier。所有处于等待的线程都会收到`BrokenBarrierError`异常\n",
    "4. `bar.abort()`：将屏障置于终止状态。这会导致调用wait()的线程引发BrokenBarrierError（**为了防止某一个进程意外终止，会造成整个进程的死锁。建议在创建Barrier指定超时时间**）\n",
    "5. `bar.n_waiting`：有多少个线程处于等待状态\n",
    "6. `bar.broken`：如果屏障处于损坏状态，则为布尔值为True\n",
    "\n",
    "---\n",
    "\n",
    "参考文章：\n",
    "```\n",
    "控制台颜色输出：\n",
    "https://www.cnblogs.com/hellojesson/p/5961570.html\n",
    "\n",
    "CountDownLatch与CyclicBarrier\n",
    "http://www.cnblogs.com/dolphin0520/p/3920397.html\n",
    "https://blog.csdn.net/a347911/article/details/53465445\n",
    "https://blog.csdn.net/carson0408/article/details/79471490\n",
    "https://blog.csdn.net/zzg1229059735/article/details/61191679\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2.3.深入篇\n",
    "\n",
    "### 2.3.1.GIL\n",
    "\n",
    "#### 1.引入\n",
    "\n",
    "什么都先不说，先看一个对比案例来引入：\n",
    "\n",
    "Python：\n",
    "```py\n",
    "def main():\n",
    "    while 1:\n",
    "        pass\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "运行后HTOP信息：`python3 1.GIL_Test.py`\n",
    "![8.python_htop.png](https://img2018.cnblogs.com/blog/1127869/201810/1127869-20181011170708882-1256032275.png)\n",
    "\n",
    "有人可能会反驳了，这是啥测试，多线程都没用到怎么体现多核？不急，再看一个案例：（注意看`htop`显示的`commad`）\n",
    "```py\n",
    "from os import cpu_count\n",
    "from multiprocessing.dummy import Pool\n",
    "\n",
    "def test(i):\n",
    "    print(f\"线程{i}开始死循环～\")\n",
    "    while True:\n",
    "        pass\n",
    "\n",
    "def main():\n",
    "    pool = Pool()  # 默认是系统核数\n",
    "    # 我是4核，你改成4或者大于4都一样，等会说为啥\n",
    "    pool.map_async(test, range(cpu_count()))\n",
    "    pool.close()\n",
    "    pool.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "看看内核使用情况～乍一看，好像是利用了多核，好好算一下==>加起来差不多就是`单核CPU的100%`嘛...\n",
    "![8.python_dummy.png](https://img2018.cnblogs.com/blog/1127869/201810/1127869-20181011214348160-1256074648.png)\n",
    "\n",
    "来看看为什么不影响：（改成5）【要想把N核CPU的核心全部跑满，就必须启动N个死循环线程】\n",
    "```py\n",
    "def main():\n",
    "    pool = Pool(5)  # 默认是系统核数\n",
    "    pool.map_async(test, range(5))\n",
    "    pool.close()\n",
    "    pool.join()\n",
    "```\n",
    "效果：（还是单核CPU充分利用）\n",
    "![8.python_why.png](https://img2018.cnblogs.com/blog/1127869/201810/1127869-20181011222235151-374928101.png)\n",
    "\n",
    "---\n",
    "\n",
    "那其他语言是不是也这样？以`NetCore`为例：`dotnet new console -o testGIL`\n",
    "```csharp\n",
    "class Program\n",
    "{\n",
    "    static void Main(string[] args)\n",
    "    {\n",
    "        var list = new List<int>() { 1, 2, 3, 4, 5 };\n",
    "        var tasks = list.AsParallel().Select(i => Task.Run(() => Test(i))).ToArray();\n",
    "        Task.WhenAll(tasks).Wait(); // 等待所有Task完成才结束\n",
    "    }\n",
    "    static void Test(int i)\n",
    "    {\n",
    "        System.Console.WriteLine($\"启动线程{i}\");\n",
    "        while (true) { }\n",
    "    }\n",
    "}\n",
    "```\n",
    "运行后HTOP信息：`dotnet testGIL.dll`\n",
    "![8.netcore_task.png](https://img2018.cnblogs.com/blog/1127869/201810/1127869-20181011215337803-521782717.png)\n",
    "\n",
    "**现在Java和Python都在模仿Net的一些优雅新语法，比如异步这块。如果你用的还是那么繁琐低效那真的好好反思一下了**\n",
    "\n",
    "如果记不得Net的知识可以点我回顾：<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9426279.html#NetCore并发编程\" target=\"_blank\">https://www.cnblogs.com/dotnetcrazy/p/9426279.html#NetCore并发编程</a>\n",
    "\n",
    "#### 2.最简单的优化～线程变进程\n",
    "\n",
    "最常见方法：线程变进程，因为是Linux，进程和线程不像Win那样性能相差那么大，其实上面代码都可以不动，就改一个地方：`multiprocessing.dummy`=>**`multiprocessing`**\n",
    "```py\n",
    "from os import cpu_count\n",
    "from multiprocessing import Pool # 就改下这就ok了\n",
    "\n",
    "def test(i):\n",
    "    print(f\"进程{i}开始死循环～\")\n",
    "    while True:\n",
    "        pass\n",
    "\n",
    "def main():\n",
    "    pool = Pool()  # 默认是系统核数\n",
    "    pool.map_async(test, range(cpu_count()))\n",
    "    pool.close()\n",
    "    pool.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "现在看看效果：\n",
    "![8.python_process.png](https://img2018.cnblogs.com/blog/1127869/201810/1127869-20181011215133768-751406491.png)\n",
    "\n",
    "很多人编程都只是利用了单核，对于今天这个多核遍布的时代，着实有点可惜了（自己买的云服务器基本上都是1核1G或者1核2G的，编程语言性能相差不大，企业用就得深入探讨优化了～）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 说说GIL\n",
    "\n",
    "Code：`https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Thread/3.GIL`\n",
    "\n",
    "**尽管Python完全支持多线程编程， 但是解释器的C语言实现部分在完全并行执行时并不是线程安全的，所以这时候才引入了GIL**\n",
    "\n",
    "解释器被一个全局解释器锁保护着，它确保任何时候都只有一个Python线程执行(保证C实现部分能线程安全) GIL最大的问题就是Python的多线程程序并不能利用多核CPU的优势 （比如一个使用了多个线程的计算密集型程序只会在一个单CPU上面运行）\n",
    "\n",
    "注意：**GIL只会影响到那些严重依赖CPU的程序（比如计算型的）如果你的程序大部分只会涉及到I/O，比如网络交互，那么使用多线程就很合适** ~ 因为它们大部分时间都在等待（线程被限制到同一时刻只允许一个线程执行这样一个执行模型。GIL会根据执行的字节码行数和时间片来释放GIL，在遇到IO操作的时候会主动释放权限给其他线程）\n",
    "\n",
    "<font style=\"color:#004cbf;\">所以Python的线程**更适用于处理`I/O`和其他需要并发执行的阻塞操作，而不是需要多处理器并行的计算密集型任务**（对于IO操作来说，多进程和多线程性能差别不大）</font>【**<a href=\"https://github.com/ray-project/ray\" target=\"_blank\">计算密集现在可以用Python的`Ray`框架</a>**】\n",
    "\n",
    "网上摘取一段关于`IO密集和计算密集`的说明：（IO密集型可以结合异步）\n",
    "```\n",
    "计算密集型任务的特点是要进行大量的计算，消耗CPU资源，比如计算圆周率、对视频进行高清解码等等，全靠CPU的运算能力。这种计算密集型任务虽然也可以用多任务完成，但是任务越多，花在任务切换的时间就越多，CPU执行任务的效率就越低，所以，要最高效地利用CPU，计算密集型任务同时进行的数量应当等于CPU的核心数。\n",
    "\n",
    "计算密集型任务由于主要消耗CPU资源，因此，代码运行效率至关重要。Python这样的脚本语言运行效率很低，完全不适合计算密集型任务。对于计算密集型任务，最好用C语言编写。\n",
    "\n",
    "第二种任务的类型是IO密集型，涉及到网络、磁盘IO的任务都是IO密集型任务，这类任务的特点是CPU消耗很少，任务的大部分时间都在等待IO操作完成（因为IO的速度远远低于CPU和内存的速度）。对于IO密集型任务，任务越多，CPU效率越高，但也有一个限度。常见的大部分任务都是IO密集型任务，比如Web应用。\n",
    "\n",
    "IO密集型任务执行期间，99%的时间都花在IO上，花在CPU上的时间很少，因此，用运行速度极快的C语言替换用Python这样运行速度极低的脚本语言，完全无法提升运行效率。对于IO密集型任务，最合适的语言就是开发效率最高（代码量最少）的语言，脚本语言是首选，C语言最差。\n",
    "```\n",
    "\n",
    "#### Process and Thread Test\n",
    "\n",
    "其实用不用多进程看你需求，不要麻木使用，Linux下还好点，Win下进程开销就有点大了（好在服务器基本上都是Linux，程序员开发环境也大多Linux了）这边只是简单测了个启动时间差距就来了，其他的都不用测试了\n",
    "\n",
    "测试Code：\n",
    "```py\n",
    "from time import sleep\n",
    "from multiprocessing import Process\n",
    "\n",
    "def test(i):\n",
    "    sleep(1)\n",
    "    print(i)\n",
    "\n",
    "def main():\n",
    "    t_list = [Process(target=test, args=(i, )) for i in range(1000)]\n",
    "    for t in t_list:\n",
    "        t.start()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "运行时间：\n",
    "```\n",
    "real\t0m3.980s\n",
    "user\t0m2.034s\n",
    "sys\t 0m3.119s\n",
    "```\n",
    "\n",
    "**操作系统几千个进程开销还是有点大的**（毕竟进程是有上线的）`ulimit -a`\n",
    "![9.MaxProcess.png](https://img2018.cnblogs.com/blog/1127869/201810/1127869-20181012165257226-1648541203.png)\n",
    "\n",
    "测试Code：\n",
    "```py\n",
    "from time import sleep\n",
    "from multiprocessing.dummy import Process\n",
    "\n",
    "def test(i):\n",
    "    sleep(1)\n",
    "    print(i)\n",
    "\n",
    "def main():\n",
    "    t_list = [Process(target=test, args=(i, )) for i in range(1000)]\n",
    "    for t in t_list:\n",
    "        t.start()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "运行时间：\n",
    "```\n",
    "real\t0m1.130s\n",
    "user\t0m0.158s\n",
    "sys\t 0m0.095s\n",
    "```\n",
    "\n",
    "`multiprocessing.dummy`里面的Process上面也说过了，就是在线程基础上加点东西使得用起来和`multiprocessing`的`Process`编程风格基本一致（本质还是线程）\n",
    "\n",
    "测试Code:\n",
    "```py\n",
    "from time import sleep\n",
    "from multiprocessing.dummy import threading\n",
    "\n",
    "def test(i):\n",
    "    sleep(1)\n",
    "    print(i)\n",
    "\n",
    "def main():\n",
    "    t_list = [threading.Thread(target=test, args=(i, )) for i in range(1000)]\n",
    "    for t in t_list:\n",
    "        t.start()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "运行时间：\n",
    "```\n",
    "real\t0m1.123s\n",
    "user\t0m0.154s\n",
    "sys\t 0m0.085s\n",
    "```\n",
    "\n",
    "其实Redis就是使用单线程和多进程的经典，它的性能有目共睹。所谓性能无非看个人能否充分发挥罢了。不然就算给你轰炸机你也不会开啊？扎心不老铁～\n",
    "\n",
    "PS：**线程和进程各有其好处，无需一棍打死，具体啥好处可以回顾之前写的进程和线程篇～**\n",
    "\n",
    "---\n",
    "\n",
    "#### 3.利用共享库来扩展\n",
    "\n",
    "#### C系扩展\n",
    "\n",
    "GIL是Python解释器设计的历史遗留问题，多线程编程，模型复杂，容易发生冲突，必须用锁加以隔离，同时，又要小心死锁的发生。Python解释器由于设计时有GIL全局锁，导致了多线程无法利用多核。计算密集型任务要真正利用多核，除非重写一个不带GIL的解释器（`PyPy`）如果一定要通过多线程利用多核，可以通过C扩展来实现（**Python很多模块都是用C系列写的，所以用C扩展也就不那么奇怪了**）\n",
    "\n",
    "只要用C系列写个简单功能（不需要深入研究高并发），然后使用`ctypes`导入使用就行了：\n",
    "```c\n",
    "#include <stdio.h>  \n",
    "\n",
    "void test()  \n",
    "{  \n",
    "  while(1){}\n",
    "}\n",
    "```\n",
    "编译成共享库：**`gcc 2.test.c -shared -o libtest.so`**\n",
    "![9.共享库.png](https://img2018.cnblogs.com/blog/1127869/201810/1127869-20181012174437403-37264231.png)\n",
    "\n",
    "使用Python运行指定方法：（`太方便了，之前一直以为C#调用C系列最方便，用完Python才知道更简方案`）\n",
    "```py\n",
    "from ctypes import cdll\n",
    "from os import cpu_count\n",
    "from multiprocessing.dummy import Pool\n",
    "\n",
    "def main():\n",
    "    # 加载C共享库（动态链接库）\n",
    "    lib = cdll.LoadLibrary(\"./libtest.so\")\n",
    "\n",
    "    pool = Pool()  # 默认是系统核数\n",
    "    pool.map_async(lib.test, range(cpu_count()))\n",
    "    pool.close()\n",
    "    pool.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "看看这时候HTOP的信息：（充分利用多核）【**ctypes在调用C时会自动释放GIL**】\n",
    "![9.ctypes.png](https://img2018.cnblogs.com/blog/1127869/201810/1127869-20181012184752135-732557811.png)\n",
    "\n",
    "#### Go扩展\n",
    "\n",
    "利用Go写个死循环，然后编译成so动态链接库（共享库）：\n",
    "```go\n",
    "package main\n",
    "import \"C\"\n",
    "\n",
    "//export test\n",
    "func test(){\n",
    "\tfor true{\n",
    "    }\n",
    "}\n",
    "\n",
    "func main() {\n",
    "\ttest()\n",
    "}\n",
    "```\n",
    "\n",
    "<font style=\"color:red;\">**非常重要的事情：`//export test`一定要写，不然就被自动改成其他名字（我当时被坑过）**</font>\n",
    "\n",
    "Python调用和上面一样：\n",
    "```py\n",
    "from ctypes import cdll\n",
    "from os import cpu_count\n",
    "from multiprocessing.dummy import Pool\n",
    "\n",
    "def main():\n",
    "    # 加载动态链接库\n",
    "    lib = cdll.LoadLibrary(\"./libtestgo.so\")\n",
    "\n",
    "    pool = Pool()  # 默认是系统核数\n",
    "    pool.map_async(lib.test, range(cpu_count()))\n",
    "    pool.close()\n",
    "    pool.join()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "效果：`go build -buildmode=c-shared -o libtestgo.so 2.test.go`\n",
    "![9.golang.png](https://img2018.cnblogs.com/blog/1127869/201810/1127869-20181012211715940-910630688.png)\n",
    "\n",
    "---\n",
    "\n",
    "题外话～如果想等CPython的GIL消失可以先看一个例子：MySQL把大锁改成各个小锁花了5年。在是在MySQL有专门的团队和公司前提下，而Python完全靠社区重构就太慢了\n",
    "\n",
    "速度方面微软除外，更新快本来是好事，但是动不动断层更新，这学习成本就太大了(这也是为什么Net能深入的人比较少的原因：人家刚深入一个，你就淘汰一个了...)\n",
    "\n",
    "可能还有人不清楚，贴下官方推荐技术吧（`NetCore`、`Orleans`、`EFCore`、`ML.Net`、`CoreRT`）\n",
    "```\n",
    "https://github.com/aspnet/AspNetCore\n",
    "\n",
    "https://github.com/aspnet/EntityFrameworkCore\n",
    "\n",
    "https://github.com/dotnet/machinelearning\n",
    "\n",
    "https://github.com/dotnet/orleans\n",
    "\n",
    "https://github.com/aspnet/Mvc\n",
    "\n",
    "https://github.com/dotnet/corert\n",
    "```\n",
    "\n",
    "课外拓展：\n",
    "```\n",
    "用go语言给python3开发模块\n",
    "https://www.jianshu.com/p/40e069954804\n",
    "https://blog.filippo.io/building-python-modules-with-go-1-5\n",
    "\n",
    "Python与C/C++相互调用\n",
    "https://www.cnblogs.com/apexchu/p/5015961.html\n",
    "\n",
    "使用C/C++代码编写Python模块\n",
    "https://www.cnblogs.com/silvermagic/p/9087896.html\n",
    "\n",
    "快速实现python c扩展模块\n",
    "https://www.cnblogs.com/chengxuyuancc/p/6374239.html\n",
    "\n",
    "Python的C语言扩展\n",
    "https://python3-cookbook.readthedocs.io/zh_CN/latest/chapters/p15_c_extensions.html\n",
    "\n",
    "python调用golang生成的so库\n",
    "https://studygolang.com/articles/10228\n",
    "https://www.cnblogs.com/huangguifeng/p/8931837.html\n",
    "\n",
    "python调用golang并回调\n",
    "https://blog.csdn.net/gtd138/article/details/79801235\n",
    "\n",
    "Python3.x AttributeError: libtest.so: undefined symbol: fact\n",
    "https://www.cnblogs.com/tanglizi/p/8965230.html\n",
    "```\n",
    "\n",
    "#### 4.运行在其他编译器上\n",
    "\n",
    "**先看最重要的一点，一旦运行在其他编译器意味着很多Python第三方库`可能`就不能用了，相对来说`PyPy`兼容性是最好的了**\n",
    "\n",
    "如果是`Python2`系列我推荐谷歌的<a href=\"https://github.com/google/grumpy\" target=\"_blank\"><b>grumpy</b></a>\n",
    "```\n",
    "Grumpy是一个 Python to Go 源代码转换编译器和运行时。旨在成为CPython2.7的近乎替代品。关键的区别在于它将Python源代码编译为Go源代码，然后将其编译为本机代码，而不是字节码。这意味着Grumpy没有VM\n",
    "\n",
    "已编译的Go源代码是对Grumpy运行时的一系列调用，Go库提供与 Python C API类似的目的\n",
    "```\n",
    "\n",
    "如果是`Python3`系列，可以使用**`PyPy`** `PythonNet` `Jython3` `ironpython3`等等\n",
    "\n",
    "**PyPy**:<a href=\"https://bitbucket.org/pypy/pypy\" target=\"_blank\">https://bitbucket.org/pypy/pypy</a>\n",
    "\n",
    "Net方向：\n",
    "```\n",
    "https://github.com/pythonnet/pythonnet\n",
    "https://github.com/IronLanguages/ironpython3\n",
    "```\n",
    "\n",
    "Java方向：\n",
    "```\n",
    "https://github.com/jython/jython3\n",
    "```\n",
    "\n",
    "Other：\n",
    "```\n",
    "源码：https://github.com/sbinet/go-python\n",
    "参考：https://studygolang.com/articles/13019\n",
    "\n",
    "可惜CoreRT一直没完善，不然就Happy了\n",
    "https://github.com/dotnet/corert\n",
    "```\n",
    "\n",
    "`经验`：**平时基本上多线程就够用了，如果想多核利用-多进程基本上就搞定了（分布式走起）实在不行一般都是分析一下性能瓶颈在哪，然后写个扩展库**\n",
    "\n",
    "如果需要和其他平台交互才考虑上面说的这些项目。如果是Web项目就更不用担心了，现在哪个公司还不是混用？`JavaScript and Python and Go or Java or NetCore`。基本上上点规模的公司都会用到Python，之前都是`Python and Java`搭配使用，这几年开始慢慢变成`Python and Go or NetCore`搭配使用了~\n",
    "\n",
    "下集预估：`Actor模型` and `消息发布/订阅模型`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.3.2.Actor\n",
    "\n",
    "\n",
    "#### 1.Actor引入\n",
    "\n",
    "可能有些朋友不清楚`Actor`是个啥？我们从场景来切入一下：\n",
    "\n",
    "以之前小明小子互刷银行流水记录为例，开始是这么写：<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9528315.html#动态死锁\" target=\"_blank\">小明小张死锁问题</a>\n",
    "```py\n",
    "def transfer(p_from, p_to, money):\n",
    "    with p_from.lock:\n",
    "        p_from.money -= money\n",
    "        sleep(1)  # 模拟网络延迟\n",
    "        with p_to.lock:\n",
    "            p_to += money\n",
    "```\n",
    "乍一看好像没问题，其实容易出现死锁现象，比如小明给小张转1000：\n",
    "1. 小明先获取自己的锁，然后准备获取小张的锁\n",
    "2. 这时候遇到小张给小明转账（小张把自己的锁先获取了）\n",
    "3. 于是就死锁了，图示：\n",
    "![10.死锁.png](https://img2018.cnblogs.com/blog/1127869/201810/1127869-20181016154412609-679617897.png)\n",
    "\n",
    "解决也很简单，前面也说了好几种方法，这边再说下Python独有的快速解决法：（<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9528315.html#1.加锁机制\" target=\"_blank\">完整版点我</a>）\n",
    "```py\n",
    "from contextlib import contextmanager  # 引入上下文管理器\n",
    "\n",
    "@contextmanager\n",
    "def lock_manager(*args):\n",
    "    # 先排个序（按照id排序）\n",
    "    args = sorted(args, key=lambda x: id(x))\n",
    "\n",
    "    try:\n",
    "        for lock in args:\n",
    "            lock.acquire()\n",
    "        yield\n",
    "    finally:\n",
    "        # 先释放最后加的锁（倒序释放）\n",
    "        for lock in reversed(args):\n",
    "            lock.release()\n",
    "```\n",
    "调用就比较简单了：(<a href=\"https://www.cnblogs.com/dotnetcrazy/p/9528315.html#动态死锁\" target=\"_blank\">通用方法点我</a>)\n",
    "```py\n",
    "def transfer(p_from, p_to, money):\n",
    "    with lock_manager(p_from.lock,p_to.lock):\n",
    "        p_from.money -= money\n",
    "        p_to += money\n",
    "```\n",
    "\n",
    "#### 2.Actor概念\n",
    "\n",
    "上面的引入用了线程的各种知识，很多新手都直接崩溃，又是`死锁`又是`活锁`接着还衍生出了`算法`以及`线程安全`、`线程通信`等等一大堆东西要掌握，**那有没有一种简单的方法，把线程的概念隐藏起来，然后所有的操作都不用加锁呢？**这样就是是新手也能快速上手了～有！这便是我们今天要说的`Actor`\n",
    "\n",
    "那啥是`Actor`呢？咱们去PPT里画个简化版的图：\n",
    "![10.Actor1.jpg](https://img2018.cnblogs.com/blog/1127869/201810/1127869-20181016164646487-197832011.jpg)\n",
    "\n",
    "我存款就发个消息到`MailBox`里面，我转账也发个消息到`MailBox`里面。不管是有一个消息，还是有100个消息，我统统放到队列中，然后让`Actor`对象顺序处理，这样就我不用管什么锁不锁的也不用管别人了～\n",
    "\n",
    "别人需要接收我的转账就到我的`MailBox`里面拉消息即可，要是我转账的时候余额不够了它就给我的`MailBox`里面发送条余额不够的消息\n",
    "\n",
    "![10.Actor2.jpg](https://img2018.cnblogs.com/blog/1127869/201810/1127869-20181016164943553-1149876475.jpg)\n",
    "\n",
    "可能有些人会说了，那我用队列`Queue`不就得了，好像也差不多啊？看起来的确差不多，但是`Queue`是同步操作，就算用了异步发送消息也要监听和重试，太麻烦了～\n",
    "\n",
    "其实你也可以把`Actor`理解为封装的`Queue`，要干什么就异步发个消息到`Actor`的`MailBox`里，这样就不是同步操作，而且也不用关注那些杂七杂八的东西了。\n",
    "\n",
    "**切换到进程也很方便，把`Actor`相互通信的`Queue`换成进程版的即可，想要分布式部署也一样，换成`MQ`或者`Redis`就好了，代码基本上不需要什么改动**\n",
    "\n",
    "---\n",
    "\n",
    "**概念汇总**：\n",
    "\n",
    "`Actor`：`Actor`之间不共享状态，但是会接收别的`Actor`发送的异步消息，处理的过程中，会改变内部状态，也可能向别的`Actor`发送消息\n",
    "\n",
    "`Message`：消息是不可变的， 它的发送都是异步的，`Actor`内部有个`MailBox`来缓存消息\n",
    "\n",
    "`MailBox`：`Actor`内部缓存消息的邮箱，其他`Actor`发送的消息都放到这里，然后被本`Actor`处理，类似有多个生产者和一个消费者的`Queue`\n",
    "\n",
    "#### 3.简单实现\n",
    "\n",
    "##### 精简版\n",
    "\n",
    "先定义一个含有`Actor、MailBox`的精简版`Actor`：\n",
    "```py\n",
    "from multiprocessing.dummy import Queue\n",
    "\n",
    "class Actor(object):\n",
    "    def __init__(self):\n",
    "        # Actor内部的消息缓存队列\n",
    "        self.__mailbox = Queue()\n",
    "\n",
    "    def send(self, msg):\n",
    "        self.__mailbox.put(msg)\n",
    "\n",
    "    def recv(self):\n",
    "        return self.__mailbox.get()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    xiaoming = Actor()\n",
    "    xiaoming.send(\"存款\")\n",
    "    msg = xiaoming.recv()\n",
    "    print(msg)\n",
    "```\n",
    "输出：（通过`send`发送消息，通过`recv`接收消息）\n",
    "```\n",
    "存款\n",
    "```\n",
    "\n",
    "##### 简单版\n",
    "\n",
    "用生成器(`yield`)实现一个简单版的：\n",
    "```py\n",
    "def actor():\n",
    "    while True:\n",
    "        try:\n",
    "            msg = yield  # 获取消息\n",
    "            print(msg, end=\"\")\n",
    "        except RuntimeError:\n",
    "            print('Actor退出')\n",
    "\n",
    "p = actor()\n",
    "next(p)  # 准备接收\n",
    "p.send(\"你好～\")\n",
    "p.send(\"小明\")\n",
    "p.close()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "你好～ 小明\n",
    "```\n",
    "\n",
    "---\n",
    "\n",
    "**完善**：和线程结合定义一个简单版的`Actor`（向用户屏蔽繁琐的线程）："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "class ActorExit(Exception):\n",
    "    \"\"\"用来标记Actor退出（特殊的哨兵值）\"\"\"\n",
    "    pass\n",
    "\n",
    "class BaseActor(object):\n",
    "    def __init__(self):\n",
    "        \"\"\"queue：Actor内部的邮箱队列\"\"\"\n",
    "        self.__mailbox = Queue()\n",
    "\n",
    "    def recv(self):\n",
    "        \"\"\"Actor接受消息\"\"\"\n",
    "        msg = self.__mailbox.get()\n",
    "        if msg is ActorExit:\n",
    "            # 抛出异常（模版方法会处理）\n",
    "            raise ActorExit\n",
    "        return msg\n",
    "\n",
    "    def send(self, msg):\n",
    "        \"\"\"Actor发送消息\"\"\"\n",
    "        self.__mailbox.put(msg)\n",
    "\n",
    "    def close(self):\n",
    "        \"\"\"发送结束标识\"\"\"\n",
    "        self.send(ActorExit)\n",
    "\n",
    "    def start(self):\n",
    "        self.__terminated_event = Event()  # 为Join服务\n",
    "        t = threading.Thread(target=self.__templet)\n",
    "        t.setDaemon(True)  # 设置为守护线程\n",
    "        t.start()\n",
    "\n",
    "    def __templet(self):\n",
    "        \"\"\"模版方法（run会被子类重写）\"\"\"\n",
    "        try:\n",
    "            self.run()  # 执行Run代码\n",
    "        except ActorExit:\n",
    "            pass  # 防止线程挂掉\n",
    "        finally:\n",
    "            # 设置Event标识\n",
    "            self.__terminated_event.set()\n",
    "\n",
    "    def join(self):\n",
    "        # Event在set之后便结束等待\n",
    "        self.__terminated_event.wait()\n",
    "\n",
    "    def run(self):\n",
    "        \"\"\"由子类实现即可\"\"\"\n",
    "        pass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在再写小明小张转账互刷的`Code`就简单了：\n",
    "```py\n",
    "from BaseActor import BaseActor\n",
    "\n",
    "class PeopleActor(BaseActor):\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "        self.money = 5000  # 每个人有5000块\n",
    "\n",
    "    def run(self):\n",
    "        while True:\n",
    "            msg = self.recv()\n",
    "            # 转账msg为负，收账msg为正\n",
    "            if isinstance(msg, int):\n",
    "                self.money += msg\n",
    "\n",
    "    @classmethod\n",
    "    def transfer(cls, p_from, p_to, money):\n",
    "        p_from.send(-money)\n",
    "        p_to.send(money)\n",
    "\n",
    "\n",
    "def main():\n",
    "    xiaoming = PeopleActor()\n",
    "    xiaozhang = PeopleActor()\n",
    "    xiaopan = PeopleActor()\n",
    "    # 批量启动\n",
    "    for actor in (xiaoming, xiaozhang, xiaopan):\n",
    "        actor.start()\n",
    "\n",
    "    print(f\"[转账前]小张：{xiaozhang.money},小明：{xiaoming.money},小潘：{xiaopan.money}\")\n",
    "    for i in range(5):\n",
    "        if i == 2:\n",
    "            # 【测试】转账过程中小潘还了小明500元\n",
    "            PeopleActor.transfer(xiaopan, xiaoming, 500)\n",
    "        # 小明转账1000给小张\n",
    "        PeopleActor.transfer(xiaoming, xiaozhang, 1000)\n",
    "        # 小张转账1000给小明\n",
    "        PeopleActor.transfer(xiaozhang, xiaoming, 1000)\n",
    "        print(f\"[本次转账]小张:{xiaozhang.money},小明:{xiaoming.money},小潘:{xiaopan.money}\")\n",
    "\n",
    "    for actor in (xiaoming, xiaozhang, xiaopan):\n",
    "        actor.close()\n",
    "        actor.join()\n",
    "    print(f\"[转账后]小张：{xiaozhang.money},小明：{xiaoming.money},小潘：{xiaopan.money}\")\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()\n",
    "```\n",
    "输出：（`都不用引入Queue、Thread这些了`）\n",
    "```\n",
    "[转账前]小张：5000,小明：5000,小潘：5000\n",
    "[本次转账]小张:5000,小明:5000,小潘:5000\n",
    "[本次转账]小张:5000,小明:5000,小潘:5000\n",
    "[本次转账]小张:5000,小明:5000,小潘:5000\n",
    "[本次转账]小张:5000,小明:5500,小潘:4500\n",
    "[本次转账]小张:5000,小明:5500,小潘:4500\n",
    "[转账后]小张：5000,小明：5500,小潘：4500\n",
    "```\n",
    "\n",
    "#### 扩展部分\n",
    "\n",
    "##### 执行对应方法\n",
    "\n",
    "`Actor`的魅力就在于它的简单，你只需要`send`和`recv`其他复杂的部分根本不用过问，扩展也比较方便，比如**以元组形式传递标签消息，让actor执行不同的操作**：\n",
    "```py\n",
    "from BaseActor import BaseActor\n",
    "\n",
    "class TagActor(BaseActor):\n",
    "    def run(self):\n",
    "        while True:\n",
    "            tag, *args = self.recv()\n",
    "            getattr(self, 'do_' + tag)(*args)\n",
    "\n",
    "    def do_A(self, x):\n",
    "        print('方法A', x)\n",
    "\n",
    "    def do_B(self, x, y):\n",
    "        print('方法B', x, y)\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    a = TagActor()\n",
    "    a.start()\n",
    "    a.send(('A', 1))  # Invokes do_A(1)\n",
    "    a.send(('B', 2, 3))  # Invokes do_B(2,3)\n",
    "    a.close()\n",
    "    a.join()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "方法A 1\n",
    "方法B 2 3\n",
    "```\n",
    "\n",
    "##### 执行指定方法并返回\n",
    "\n",
    "先不看怎么写，遇到这种需求首先看看平时怎么用的，以Net为例，联想到Task：\n",
    "```py\n",
    "task = Task.Run(xxx)\n",
    "task.Result # 阻塞等\n",
    "```\n",
    "这样大体思路就有了，我们需要一个`Actor`类来处理执行和一个`Result`类返回最终结果：\n",
    "```py\n",
    "from BaseActor import BaseActor\n",
    "from multiprocessing.dummy import Event\n",
    "\n",
    "\n",
    "class TaskResult(object):\n",
    "    def __init__(self):\n",
    "        self.__event = Event()\n",
    "        self.__result = None\n",
    "\n",
    "    def result(self):\n",
    "        # 阻塞等结果\n",
    "        self.__event.wait()\n",
    "        return self.__result\n",
    "\n",
    "    def set_result(self, value):\n",
    "        self.__result = value\n",
    "        self.__event.set()  # 标记执行完毕\n",
    "\n",
    "\n",
    "class ActorTask(BaseActor):\n",
    "    def apply_async(self, func, *args, **kwagrs):\n",
    "        self.r = TaskResult()\n",
    "        self.send((func, args, kwagrs))\n",
    "        return self.r\n",
    "\n",
    "    def run(self):\n",
    "        func, args, kvargs = self.recv()\n",
    "        # 执行指定方法并return返回值\n",
    "        value = func(*args, **kvargs)\n",
    "        self.r.set_result(value)\n",
    "\n",
    "\n",
    "def test_add(a, b):\n",
    "    return a + b\n",
    "\n",
    "\n",
    "actor = ActorTask()\n",
    "actor.start()\n",
    "task = actor.apply_async(test_add, 1, 2)\n",
    "print(task.result())\n",
    "actor.close()\n",
    "actor.join()\n",
    "```\n",
    "\n",
    "#### `Actor`框架\n",
    "\n",
    "**`Actor`模型非常适用于多个组件独立工作，相互之间仅仅依靠消息传递的情况** 如果想在多个组件之间维持一致的状态，那就不方便了，需要使用一些`Actor`的框架\n",
    "\n",
    "Java最出名的就是`Akka`，这几年貌似 **`Quasar`** 用的挺多（如果有其他常用的Actor模型可以补充一下）\n",
    "\n",
    "Net起初是用的`Akka.Net`，后来官方出了 **`Orleans`**\n",
    "\n",
    "Golang现在是 **`ProtoActor`** 比较火，支持`Go、Net、Python、JS、Java`，一般混合编程的公司都会选择这款\n",
    "```\n",
    "https://github.com/AsynkronIT/protoactor-go\n",
    "https://github.com/AsynkronIT/protoactor-dotnet\n",
    "https://github.com/AsynkronIT/protoactor-dotnet\n",
    "```\n",
    "\n",
    "Python以前`Pykka`比较火，现在更推荐 **`Ray`** or **`pulsar`**\n",
    "```\n",
    "https://quantmind.github.io/pulsar\n",
    "https://github.com/quantmind/pulsar\n",
    "\n",
    "https://github.com/ray-project/ray\n",
    "https://ray.readthedocs.io/en/latest\n",
    "```\n",
    "\n",
    "进一步理解Actor可以阅读以下源码：\n",
    "```\n",
    "https://github.com/jodal/pykka\n",
    "\n",
    "https://github.com/kquick/Thespian\n",
    "\n",
    "https://github.com/tamland/python-actors\n",
    "\n",
    "https://github.com/xinhuang/async-actor\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.3.3.发布订阅\n",
    "\n",
    "上节回顾：<a href=\"https://mp.weixin.qq.com/s?__biz=MzIyOTA3NzUwMQ==&mid=2649747891&idx=1&sn=e92dbe6fa074f6cbbb71d06c0f37d14e&chksm=f0536921c724e037babd22f6a45885172f3eaea2c39a8b3e54ada2ca92562b1976a01d62765b&scene=21#wechat_redirect\" target=\"_blank\">线程篇～Actor专题</a>\n",
    "\n",
    "看个需求：**你有一个基于线程通信的程序，想让它们实现`发布/订阅`模式的消息通信**\n",
    "\n",
    "这个有点像生产消费者模型，但要实现发布/订阅的消息通信模式，通常要引入一个单独的**`网关`|`交换机`**对象作为所有消息的中介\n",
    "\n",
    "PS：**我们一般不直接将消息从一个任务发送到另一个，而是将其发送给`网关`|`交换机`， 然后由它发送给一个或多个被关联任务**\n",
    "\n",
    "通俗讲：\n",
    "1. 一个交换机就是维护**订阅者的集合**\n",
    "2. 提供**绑定**（`attach`）**解绑**（`detach`）**发送**（`send`）这些方法\n",
    "3. 每个交换机通过一个**`key`**来定位（`get_exchange(key)`返回一个`Exchange`对象）\n",
    "4. 批量通知订阅者可以把消息发送给一个指定`key`的交换机\n",
    "    - 然后交换机会将它们发送给被绑定的订阅者\n",
    "\n",
    "看个例子："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from collections import defaultdict  # dict的子类\n",
    "\n",
    "# 交换机（发布者）\n",
    "class Exchange(object):\n",
    "    def __init__(self):\n",
    "        # 订阅者集合\n",
    "        self.__subscribers = set()\n",
    "\n",
    "    # 添加一个Task到订阅者集合中\n",
    "    def attach(self, task):\n",
    "        self.__subscribers.add(task)\n",
    "\n",
    "    # 把Task从订阅者集合中移除\n",
    "    def detach(self, task):\n",
    "        self.__subscribers.remove(task)\n",
    "\n",
    "    def send(self, msg):\n",
    "        for subscriber in self.__subscribers:\n",
    "            # 调用订阅者里面的send方法\n",
    "            subscriber.send(msg)\n",
    "\n",
    "exchange_dict = defaultdict(Exchange)\n",
    "\n",
    "def get_exchange(key):\n",
    "    return exchange_dict[key]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "test\n",
      "test\n"
     ]
    }
   ],
   "source": [
    "# 定义一个Task\n",
    "class BaseTask(object):\n",
    "    def send(self, msg):\n",
    "        print(msg)\n",
    "\n",
    "\n",
    "# 比如获取一个key是shop的交换机\n",
    "exc = get_exchange(\"shop\")\n",
    "\n",
    "# 然后把任务1和2添加到交换机内\n",
    "task1 = BaseTask()\n",
    "task2 = BaseTask()\n",
    "exc.attach(task1)\n",
    "exc.attach(task2) # 分离使用：detach\n",
    "\n",
    "# 这时候要是群发消息就简单了：\n",
    "exc.send(\"test\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "订阅者可能和交换机不在同一个机器上，这时候想显示`log`输出就需要设置下：\n",
    "\n",
    "其实也很简单，在交换机这台PC上弄个订阅者即可：\n",
    "```py\n",
    "# 交换机上的订阅者\n",
    "class PrintMessages:\n",
    "    def __init__(self):\n",
    "        self.count = 0\n",
    "\n",
    "    def send(self, msg):\n",
    "        self.count += 1\n",
    "        print(f\"msg[{self.count}]: {msg}\")\n",
    "\n",
    "exc = get_exchange('shop')\n",
    "exc.attach(PrintMessages())\n",
    "\n",
    "\n",
    "# 定义一个Task\n",
    "class BaseTask(object):\n",
    "    def send(self, msg):\n",
    "        print(msg)\n",
    "\n",
    "# 比如获取一个key是shop的交换机\n",
    "exc = get_exchange(\"shop\")\n",
    "\n",
    "# 然后把任务1和2添加到交换机内（模拟其他PC的订阅者）\n",
    "task1 = BaseTask()\n",
    "task2 = BaseTask()\n",
    "exc.attach(task1)\n",
    "exc.attach(task2)  # 分离使用：detach\n",
    "\n",
    "# 这时候要是群发消息就简单了：\n",
    "exc.send(\"test\")\n",
    "```\n",
    "\n",
    "PS：注意一个交换机可能存在的Bug（对于订阅者的正确绑定和解绑：为了正确的管理资源，每一个绑定的订阅者必须最终要解绑）\n",
    "```py\n",
    "exc = get_exchange('key')\n",
    "exc.attach(some_task)\n",
    "try:\n",
    "    ...\n",
    "finally:\n",
    "    exc.detach(some_task)\n",
    "```\n",
    "\n",
    "这个和使用文件、锁等很像，如果怕忘记，可以借助`上下文管理器`在交换机上添加个方法\n",
    "\n",
    "eg，以上面代码为例，进行改造："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from contextlib import contextmanager\n",
    "from collections import defaultdict\n",
    "\n",
    "class Exchange(object):\n",
    "    # 定义一个订阅者集合\n",
    "    def __init__(self):\n",
    "        self.__subscribers = set()\n",
    "\n",
    "    # 定义一个附加任务的方法\n",
    "    def attach(self, task):\n",
    "        self.__subscribers.add(task)\n",
    "\n",
    "    # 定义一个分离任务的方法\n",
    "    def detach(self, task):\n",
    "        self.__subscribers.remove(task)\n",
    "\n",
    "    # 知识回顾：http://www.cnblogs.com/dotnetcrazy/p/9528315.html#锁专题扩展\n",
    "    @contextmanager\n",
    "    def subscribe(self, *tasks):\n",
    "        # 防止用户忘记解绑任务\n",
    "        for task in tasks:\n",
    "            self.attach(task)\n",
    "        # 不要放在循环内（容易出错）\n",
    "        try:\n",
    "            yield\n",
    "        finally:\n",
    "            for task in tasks:\n",
    "                self.detach(task)\n",
    "\n",
    "    # 批量调用订阅者们的send方法\n",
    "    def send(self, msg):\n",
    "        for subscribe in self.__subscribers:\n",
    "            subscribe.send(msg)\n",
    "\n",
    "exchange_dict = defaultdict(Exchange)\n",
    "\n",
    "def get_exchange(key):\n",
    "    return exchange_dict[key]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "test\n",
      "test\n"
     ]
    }
   ],
   "source": [
    "# 定义一个Task\n",
    "class BaseTask(object):\n",
    "    def send(self, msg):\n",
    "        print(msg)\n",
    "\n",
    "# 比如获取一个key是shop的交换机\n",
    "exc = get_exchange(\"shop\")\n",
    "\n",
    "# 然后把任务1和2添加到交换机内\n",
    "task1 = BaseTask()\n",
    "task2 = BaseTask()\n",
    "\n",
    "# 把任务批量扔进去即可\n",
    "with exc.subscribe(task1, task2):\n",
    "    exc.send(\"test\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "其实还可以各种扩展，比如：\n",
    "1. 交换机可以实现一整个消息通道集合或提供交换机名称的模式匹配规则\n",
    "2. 扩展到分布式计算程序中（eg：将消息路由到不同机器上的任务中）\n",
    "\n",
    "### GIL扩展\n",
    "\n",
    "上次说了这么生成`so共享库`,然后通过`ctypes`模块来调用，简单回顾下：<a href=\"https://mp.weixin.qq.com/s?__biz=MzIyOTA3NzUwMQ==&mid=2649747882&idx=1&sn=cd9c65042ef8336a2a13bea1497bfeaa&chksm=f0536938c724e02e1d0a1302f7912fd64db95ba251e4af5de416821f49a90d062396a2380476&scene=21#wechat_redirect\" target=\"_blank\">线程深入篇之～GIL专题</a>\n",
    "\n",
    "#### 1.共享库的测试\n",
    "\n",
    "之前有人问之前的方式是否跨平台，当时是在Ubuntu下的，我们现在去CentOS测试下：\n",
    "\n",
    "首先确保系统是多核（单核测试没有意义）\n",
    "![11.多核保证.png](https://img2018.cnblogs.com/blog/1127869/201812/1127869-20181217144351728-585789214.png)\n",
    "\n",
    "现在看下测试结果：（和Ubuntu效果一样，不需要修改任何代码）\n",
    "![11.centos.png](https://img2018.cnblogs.com/blog/1127869/201812/1127869-20181217144848541-252922925.png)\n",
    "\n",
    "PS：**`CentOS7`没有安装`htop`的**：\n",
    "```\n",
    "yum install epel-release -y\n",
    "yum install htop -y\n",
    "```\n",
    "\n",
    "#### 2.C编写Python3模块\n",
    "\n",
    "现在准备说的是用`C`来写`Python`模块（方便使用）先看下应用场景：\n",
    "1. 提升性能（突破GIL）\n",
    "2. 核心业务代码保密\n",
    "3. 方便调用（比`ctypes`的方式方便）\n",
    "\n",
    "大概流程：\n",
    "1. 编写C系列代码\n",
    "2. 为了调用方便，把`c`和`python`进行下类型转换（**包裹函数**）\n",
    "3. 打包（`setup.py`）\n",
    "\n",
    "#### 3.简单案例\n",
    "\n",
    "Github地址：<a href=\"https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Thread/3.GIL/Ext\" target=\"_blank\">https://github.com/lotapp/BaseCode/tree/master/python/5.concurrent/Thread/3.GIL/Ext</a>\n",
    "\n",
    "1.先来个简单的案例：（你可以把`C`系列的三个文件放在一个里面）\n",
    "```c\n",
    "#include <stdio.h>\n",
    "\n",
    "// 模拟一个耗cpu的操作\n",
    "int fib(int n)\n",
    "{\n",
    "    if (n < 3)\n",
    "        return 1;\n",
    "    return fib(n - 1) + fib(n - 2);\n",
    "}\n",
    "\n",
    "int main(void)\n",
    "{\n",
    "    printf(\"fib(30)=%d == 832040\\n\", fib(30));\n",
    "    return 0;\n",
    "}\n",
    "```\n",
    "先测试下c文件有没有问题：`gcc [-Wall] dnt.c -o dnt`\n",
    "```\n",
    "fib(30)=832040 == 832040\n",
    "```\n",
    "\n",
    "2.把对应的**头文件**也写一下：（这个可以参考`golang`生成动态库时产生的`头文件`）\n",
    "```c\n",
    "#ifndef DNT_H_\n",
    "#define DNT_H_\n",
    "\n",
    "int fib(int n);\n",
    "\n",
    "#endif\n",
    "```\n",
    "\n",
    "3.写一个包裹函数：`pack.c`（**和Python2略有不同**）\n",
    "```c\n",
    "#include \"Python.h\" // 引入Python提供的头文件\n",
    "#include \"dnt.h\"    // 引入自己定义的头文件\n",
    "\n",
    "// 模块名_函数名（调用的时候：dnt.fib(30)）\n",
    "// 相当于：定义Python对应的函数名\n",
    "static PyObject *dnt_fib(PyObject *self, PyObject *args)\n",
    "{\n",
    "    int num;\n",
    "    // 把Python类型转换成C类型（用户传过来的参数）\n",
    "    if (!PyArg_ParseTuple(args, \"i\", &num))\n",
    "        return NULL;\n",
    "\n",
    "    // 把C返回类型转换成Python类型（PS:python定义变量不加修饰符）\n",
    "    // result = (PyObject *)Py_BuildValue(\"i\", fib(num));\n",
    "    return (PyObject *)Py_BuildValue(\"i\", fib(num));\n",
    "}\n",
    "\n",
    "// 这个就是一个映射关系（Python函数和C函数对应）\n",
    "static PyMethodDef dntMethods[] = {\n",
    "    // {\"函数名\", 模块名_函数名, METH_VARARGS, \"函数描述\"},\n",
    "    // METH_VARARGS：告诉解释器调用约定用于C函数的标志\n",
    "    {\"fib\", dnt_fib, METH_VARARGS, \"fib函数\"}, // dnt.fib.__doc__\n",
    "    {NULL, NULL, 0, NULL} // 固定格式\n",
    "};\n",
    "\n",
    "// 模块定义\n",
    "static struct PyModuleDef dntModule = {\n",
    "    PyModuleDef_HEAD_INIT,\n",
    "    \"dnt\",\n",
    "    NULL, // 模块文档\n",
    "    -1,\n",
    "    dntMethods // 映射数组\n",
    "};\n",
    "\n",
    "// 相当于init方法 PyMODINIT_FUNC\n",
    "void PyInit_dnt(void)\n",
    "{\n",
    "    PyModule_Create(&dntModule);\n",
    "}\n",
    "```\n",
    "\n",
    "PS：安装过`python3-dev`才会有`python.h`（CentOS叫：`python-devel`）\n",
    "\n",
    "#### `Python`和`C`对应的类型转换参数表\n",
    "\n",
    "| 格式代码 | Python类型 | C系列类型          |\n",
    "| -------- | ---------- | ------------------ |\n",
    "| **`i`**  | `int`      | `int`              |\n",
    "| **`l`**  | `long`     | `long`             |\n",
    "| **`d`**  | `float`    | `double`           |\n",
    "| **`c`**  | `str`      | `char`             |\n",
    "| **`s`**  | `str`      | `char *`           |\n",
    "| **`z`**  | `str/None` | `char */NULL`      |\n",
    "| `D`      | `complex`  | `Py_Complex *`     |\n",
    "| `O`      | `Any`   | `PyObject *`       |\n",
    "| `S`      | `str`      | `PyStringObject *` |\n",
    "\n",
    "#### `Py_BuildValue`的用法表\n",
    "\n",
    "```py\n",
    "Py_BuildValue(\"\")                                    None\n",
    "Py_BuildValue(\"i\", 123)                              123\n",
    "Py_BuildValue(\"iii\", 123, 456, 789)                  (123, 456, 789)\n",
    "Py_BuildValue(\"s\", \"hello\")                          'hello'\n",
    "Py_BuildValue(\"y\", \"hello\")                          b'hello'\n",
    "Py_BuildValue(\"ss\", \"hello\", \"world\")                ('hello', 'world')\n",
    "Py_BuildValue(\"s#\", \"hello\", 4)                      'hell'\n",
    "Py_BuildValue(\"y#\", \"hello\", 4)                      b'hell'\n",
    "Py_BuildValue(\"()\")                                  ()\n",
    "Py_BuildValue(\"(i)\", 123)                            (123,)\n",
    "Py_BuildValue(\"(ii)\", 123, 456)                      (123, 456)\n",
    "Py_BuildValue(\"(i,i)\", 123, 456)                     (123, 456)\n",
    "Py_BuildValue(\"[i,i]\", 123, 456)                     [123, 456]\n",
    "Py_BuildValue(\"{s:i,s:i}\",\"abc\", 123, \"def\", 456)    {'abc': 123, 'def': 456}\n",
    "Py_BuildValue(\"((ii)(ii)) (ii)\",1, 2, 3, 4, 5, 6)    (((1, 2), (3, 4)), (5, 6))\n",
    "```\n",
    "\n",
    "4.写一个`Python`的`Setup`：\n",
    "```py\n",
    "from distutils.core import setup, Extension\n",
    "\n",
    "mod_name = \"dnt\" # 模块名\n",
    "setup(\n",
    "    name=mod_name,\n",
    "    ext_modules=[Extension(mod_name, sources=[\"dnt.c\", \"pack.c\"])]\n",
    ")\n",
    "```\n",
    "\n",
    "5.编译测试一下（`python3 setup.py build` `python3 setup.py install`）\n",
    "![11.编译](https://img2018.cnblogs.com/blog/1127869/201812/1127869-20181217173814857-1805131557.png)\n",
    "![11.安装运行](https://img2018.cnblogs.com/blog/1127869/201812/1127869-20181217174039709-950824378.png)\n",
    "\n",
    "参考链接：\n",
    "\n",
    "Python C-API参考手册：<a href=\"https://docs.python.org/3/c-api/index.html\" target=\"_blank\">https://docs.python.org/3/c-api/index.html</a>\n",
    "\n",
    "用C系列扩展Python：<a href=\"https://docs.python.org/3/extending/extending.html\" target=\"_blank\">https://docs.python.org/3/extending/extending.html</a>\n",
    "\n",
    "使用distutils构建C和C ++扩展：<a href=\"https://docs.python.org/3/extending/building.html\" target=\"_blank\">https://docs.python.org/3/extending/building.html</a>\n",
    "\n",
    "---\n",
    "\n",
    "## 2.4.通用代码\n",
    "\n",
    "官方文档：<a href=\"https://docs.python.org/3/library/concurrent.futures.html\" target=\"_blank\">concurrent.futures--启动并行任务</a>\n",
    "\n",
    "上次说到了`yield from`，这次讲的这个就是基于`线程/进程`再结合`yield`的一个通用实现：（上节回顾：<a href=\"https://mp.weixin.qq.com/s/5d701WQG1L8mDOO-bnKXdQ\" target=\"_blank\">并发编程~协程演变过程</a>）\n",
    "\n",
    "这个是Python3.2开始有`concurrent.futures`模块，我们主要使用就2个类：`ThreadPoolExecutor`和`ProcessPoolExecutor`（本质上是对`threading`和`multiprocessing`进行了高级别的抽象，方便我们实现异步调用）\n",
    "\n",
    "**PS：如果不谈协程，那么这个代码就可以算是并发编程的通用代码了**\n",
    "\n",
    "### 1.基础案例\n",
    "\n",
    "通过使用以及看源码发现：**传参和之前稍微有点不同**\n",
    "```py\n",
    "def submit(self, fn, *args, **kwargs)\n",
    "\n",
    "def apply_async(self, func, args=(), kwds={}, callback=None, error_callback=None)\n",
    "```\n",
    "\n",
    "先看个简单的引入例子：（用法和Java一样）\n",
    "```py\n",
    "import time\n",
    "from concurrent.futures import ThreadPoolExecutor\n",
    "\n",
    "def test(name, age):\n",
    "    print(name, age)\n",
    "    time.sleep(2)\n",
    "    return \"test over\"\n",
    "\n",
    "def main():\n",
    "    with ThreadPoolExecutor() as executor:\n",
    "        # 也可以这么写：(*kwargs) submit(test, name=\"小明\", age=23)\n",
    "        future = executor.submit(test, \"小明\", 23)\n",
    "        print(future, type(future))\n",
    "        result = future.result()\n",
    "        print(result)\n",
    "        print(future, type(future))\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "```\n",
    "输出：（可以通过**`task.done()`查看任务是否执行完成**）\n",
    "```\n",
    "小明 23\n",
    "<Future at 0x19384bd7358 state=running> <class 'concurrent.futures._base.Future'>\n",
    "test over\n",
    "<Future at 0x19384bd7358 state=finished returned str> <class 'concurrent.futures._base.Future'>\n",
    "```\n",
    "\n",
    "`PoolExecutor`可以指定线程|进程数，不指定默认是：\n",
    "1. 线程：**cpu核数的5倍**\n",
    "2. 进程：**cpu核数**\n",
    "\n",
    "源码看下就懂了：\n",
    "```py\n",
    "# 线程池\n",
    "class ThreadPoolExecutor(_base.Executor):\n",
    "    def __init__(self, max_workers=None, thread_name_prefix='',\n",
    "                 initializer=None, initargs=()):\n",
    "        # 线程：**cpu核数的5倍**\n",
    "        if max_workers is None:\n",
    "            max_workers = (os.cpu_count() or 1) * 5\n",
    "\n",
    "# 进程池\n",
    "class ProcessPoolExecutor(_base.Executor):\n",
    "    def __init__(self, max_workers=None, mp_context=None,\n",
    "                 initializer=None, initargs=()):\n",
    "        # 线程：**cpu核数**\n",
    "        if max_workers is None:\n",
    "            self._max_workers = os.cpu_count() or 1\n",
    "```\n",
    "\n",
    "### 2.批量任务（`as_completed`）\n",
    "\n",
    "来个批量请求的案例：\n",
    "\n",
    "```py\n",
    "import time\n",
    "import urllib.request\n",
    "import concurrent.futures\n",
    "\n",
    "url_list = [\n",
    "    \"https://www.baidu.com\", \"https://www.qq.com\", \"https://www.sogou.com\",\n",
    "    \"https://www.cnblogs.com\"\n",
    "]\n",
    "\n",
    "def get_html(url, timeout=10):\n",
    "    with urllib.request.urlopen(url, timeout=timeout) as conn:\n",
    "        return conn.read()\n",
    "\n",
    "def main():\n",
    "    start_time = time.time()\n",
    "\n",
    "    with concurrent.futures.ThreadPoolExecutor() as executor:\n",
    "        # 用字典可以通过返回的 future 拿到 url\n",
    "        tasks = [executor.submit(get_html, url) for url in url_list]\n",
    "        # 遍历完成的 future 对象\n",
    "        for task in concurrent.futures.as_completed(tasks):\n",
    "            try:\n",
    "                result = task.result()\n",
    "            except Exception as ex:\n",
    "                print(ex)\n",
    "            else:\n",
    "                print(len(result))\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "24414\n",
    "227\n",
    "47148\n",
    "46635\n",
    "0.2839970588684082\n",
    "```\n",
    "\n",
    "PS：如果需要URL，可以这样搞：`tasks = {executor.submit(get_html, url): url for url in url_list}`\n",
    "```py\n",
    "import time\n",
    "import urllib.request\n",
    "import concurrent.futures\n",
    "\n",
    "url_list = [\n",
    "    \"https://www.baidu.com\", \"https://www.qq.com\", \"https://www.sogou.com\",\n",
    "    \"https://www.cnblogs.com\"\n",
    "]\n",
    "\n",
    "def get_html(url, timeout=10):\n",
    "    with urllib.request.urlopen(url, timeout=timeout) as conn:\n",
    "        return conn.read()\n",
    "\n",
    "def main():\n",
    "    start_time = time.time()\n",
    "\n",
    "    with concurrent.futures.ThreadPoolExecutor() as executor:\n",
    "        # 用字典可以通过返回的 future 拿到 url\n",
    "        tasks = {executor.submit(get_html, url): url for url in url_list}\n",
    "        # 遍历完成的 future 对象\n",
    "        for task in concurrent.futures.as_completed(tasks):\n",
    "            url = tasks[task]\n",
    "            try:\n",
    "                result = task.result()\n",
    "            except Exception as ex:\n",
    "                print(ex)\n",
    "            else:\n",
    "                print(url, len(result))\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "```\n",
    "输出：(取得时候`url = tasks[task]`)\n",
    "```\n",
    "https://www.baidu.com 227\n",
    "https://www.sogou.com 24414\n",
    "https://www.cnblogs.com 47148\n",
    "https://www.qq.com 46635\n",
    "0.2862071990966797\n",
    "```\n",
    "\n",
    "### 3.批量任务（`map`）\n",
    "\n",
    "上面的代码用map可以快速实现：（灵活性比`as_completed`稍微差点，合适场景下倒是挺方便）\n",
    "\n",
    "```py\n",
    "import time\n",
    "import urllib.request\n",
    "import concurrent.futures\n",
    "\n",
    "url_list = [\n",
    "    \"https://www.baidu.com\", \"https://www.qq.com\", \"https://www.sogou.com\",\n",
    "    \"https://www.cnblogs.com\"\n",
    "]\n",
    "\n",
    "def get_html(url, timeout=10):\n",
    "    with urllib.request.urlopen(url, timeout=timeout) as conn:\n",
    "        return conn.read()\n",
    "\n",
    "def main():\n",
    "    start_time = time.time()\n",
    "\n",
    "    with concurrent.futures.ThreadPoolExecutor() as executor:\n",
    "        for result in executor.map(get_html, url_list):\n",
    "            print(len(result))\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "```\n",
    "\n",
    "输出：（性能比`as_completed`高点）\n",
    "```\n",
    "227\n",
    "46388\n",
    "24414\n",
    "46979\n",
    "0.2785525321960449\n",
    "```\n",
    "\n",
    "这种方式如果也想要获取到`url`，可以借助`zip`：\n",
    "```py\n",
    "import time\n",
    "import urllib.request\n",
    "import concurrent.futures\n",
    "\n",
    "url_list = [\n",
    "    \"https://www.baidu.com\", \"https://www.qq.com\", \"https://www.sogou.com\",\n",
    "    \"https://www.cnblogs.com\"\n",
    "]\n",
    "\n",
    "def get_html(url, timeout=10):\n",
    "    with urllib.request.urlopen(url, timeout=timeout) as conn:\n",
    "        return conn.read()\n",
    "\n",
    "def main():\n",
    "    start_time = time.time()\n",
    "\n",
    "    with concurrent.futures.ThreadPoolExecutor() as executor:\n",
    "        for url, result in zip(url_list, executor.map(get_html, url_list)):\n",
    "            print(url, len(result))\n",
    "\n",
    "    print(time.time() - start_time)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "```\n",
    "\n",
    "```\n",
    "https://www.baidu.com 227\n",
    "https://www.qq.com 46330\n",
    "https://www.sogou.com 24414\n",
    "https://www.cnblogs.com 47148\n",
    "0.29399967193603516\n",
    "```\n",
    "\n",
    "### 进程池的说明\n",
    "\n",
    "和线程池用法一致，就换个名字而已(`ProcessPoolExecutor`)：\n",
    "```py\n",
    "import time\n",
    "import urllib.request\n",
    "import concurrent.futures\n",
    "\n",
    "url_list = [\n",
    "    \"https://www.baidu.com\", \"https://www.qq.com\", \"https://www.sogou.com\",\n",
    "    \"https://www.cnblogs.com\"\n",
    "]\n",
    "\n",
    "def get_html(url, timeout=10):\n",
    "    with urllib.request.urlopen(url, timeout=timeout) as conn:\n",
    "        return conn.read()\n",
    "\n",
    "def main():\n",
    "    with concurrent.futures.ProcessPoolExecutor() as executor:\n",
    "        # 用字典可以通过返回的 future 拿到 url\n",
    "        tasks = {executor.submit(get_html, url): url for url in url_list}\n",
    "        # 遍历完成的 future 对象\n",
    "        for task in concurrent.futures.as_completed(tasks):\n",
    "            url = tasks[task]\n",
    "            try:\n",
    "                result = task.result()\n",
    "            except Exception as ex:\n",
    "                print(ex)\n",
    "            else:\n",
    "                print(url, len(result))\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "https://www.sogou.com 24414\n",
    "https://www.baidu.com 227\n",
    "https://www.cnblogs.com 47148\n",
    "https://www.qq.com 46364\n",
    "```\n",
    "\n",
    "### 流程图解说\n",
    "\n",
    "官方给的系统执行流程：`https://github.com/python/cpython/blob/3.7/Lib/concurrent/futures/process.py`\n",
    "```\n",
    "|======================= In-process =====================|== Out-of-process ==|\n",
    "+----------+     +----------+       +--------+     +-----------+    +---------+\n",
    "|          |  => | Work Ids |       |        |     | Call Q    |    | Process |\n",
    "|          |     +----------+       |        |     +-----------+    |  Pool   |\n",
    "|          |     | ...      |       |        |     | ...       |    +---------+\n",
    "|          |     | 6        |    => |        |  => | 5, call() | => |         |\n",
    "|          |     | 7        |       |        |     | ...       |    |         |\n",
    "| Process  |     | ...      |       | Local  |     +-----------+    | Process |\n",
    "|  Pool    |     +----------+       | Worker |                      |  #1..n  |\n",
    "| Executor |                        | Thread |                      |         |\n",
    "|          |     +----------- +     |        |     +-----------+    |         |\n",
    "|          | <=> | Work Items | <=> |        | <=  | Result Q  | <= |         |\n",
    "|          |     +------------+     |        |     +-----------+    |         |\n",
    "|          |     | 6: call()  |     |        |     | ...       |    |         |\n",
    "|          |     |    future  |     |        |     | 4, result |    |         |\n",
    "|          |     | ...        |     |        |     | 3, except |    |         |\n",
    "+----------+     +------------+     +--------+     +-----------+    +---------+\n",
    "```\n",
    "引用一下官方分析：\n",
    "1. `executor.map`会创建多个`_WorkItem`对象，每个对象都传入了新创建的一个`Future`对象\n",
    "2. 把每个`_WorkItem`对象然后放进一个叫做`Work Items`的`dict`中，键是不同的`Work Ids`\n",
    "3. 创建一个管理`Work Ids`队列的线程 **`Local worker thread`** 它能做2件事：\n",
    "    1. 从`Work Ids`队列中获取`Work Id`通过`Work Items`找到对应的`_WorkItem`如果这个`Item`被取消了，就从`Work Items`里面把它删掉，否则重新打包成一个`_CallItem`放入`Call Q`队列中,而`executor`的那些进程会从队列中取`_CallItem`执行，并把结果封装成`_ResultItems`放入`Result Q`队列中\n",
    "    2. 从`Result Q`队列中获取`_ResultItems`，然后从`Work Items`更新对应的`Future`对象并删掉入口\n",
    "\n",
    "有了我们前面讲的知识，你再读`concurrent.futures`模块真的很轻松，大家有空可以去看看\n",
    "\n",
    "### `Future`对象\n",
    "\n",
    "简单看下`Future`对象：\n",
    "1. `cancel()`：尝试去取消调用。如果调用当前正在执行，不能被取消(`返回False`)\n",
    "    - 成功返回True，失败返回False\n",
    "2. `cancelled()`：如果调用被成功取消返回True\n",
    "3. `running()`：如果当前是否正在执行\n",
    "4. `done()`：执行成功|被取消后\n",
    "5. `result(Timeout = None)`：拿到调用返回的结果（`阻塞等`）\n",
    "6. `exception(timeout=None)`：捕获程序执行过程中的异常\n",
    "7. `add_done_callback(fn)`：将fn绑定到future对象上。当future对象被取消或完成运行时，fn函数将会被调用\n",
    "\n",
    "#### `done()`和`cancel()`案例：\n",
    "\n",
    "```py\n",
    "import time\n",
    "from concurrent.futures import ThreadPoolExecutor\n",
    "\n",
    "def test(name, age):\n",
    "    print(name, age)\n",
    "    time.sleep(2)\n",
    "    return \"test over\"\n",
    "\n",
    "def main():\n",
    "    with ThreadPoolExecutor(1) as executor:\n",
    "        future1 = executor.submit(test, \"小明\", 23)\n",
    "        future2 = executor.submit(test, \"小张\", 25)\n",
    "\n",
    "        print(f\"任务1是否完成：{future1.done()}，任务2是否完成：{future2.done()}\")\n",
    "        print(f\"任务2取消成功：{future2.cancel()}\")\n",
    "        print(f\"任务1是否完成：{future1.done()}，任务2是否完成：{future2.done()}\")\n",
    "\n",
    "        result = future1.result()\n",
    "        print(result)\n",
    "        print(f\"任务1是否完成：{future1.done()}，任务2是否完成：{future2.done()}\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "小明 23\n",
    "任务1是否完成：False，任务2是否完成：False\n",
    "任务2取消成功：True\n",
    "任务1是否完成：False，任务2是否完成：True\n",
    "test over\n",
    "任务1是否完成：True，任务2是否完成：True\n",
    "```\n",
    "\n",
    "#### `wait()`说明\n",
    "\n",
    "知识点其实就这么多了，其他的后面结合协程会继续说的，然后还有一个`wait`的用法简单说说：\n",
    "\n",
    "```py\n",
    "import time\n",
    "import urllib.request\n",
    "import concurrent.futures\n",
    "\n",
    "def get_html(url):\n",
    "    with urllib.request.urlopen(url) as conn:\n",
    "        return conn.read()\n",
    "\n",
    "def main():\n",
    "    url_list = [\n",
    "        \"https://www.baidu.com\", \"https://www.qq.com\", \"https://www.sogou.com\",\n",
    "        \"https://www.cnblogs.com\"\n",
    "    ]\n",
    "\n",
    "    with concurrent.futures.ThreadPoolExecutor() as executor:\n",
    "        tasks = {executor.submit(get_html, url): url for url in url_list}\n",
    "        # 等待全部完成\n",
    "        concurrent.futures.wait(tasks)\n",
    "        # 我们来看看状态\n",
    "        for task in tasks:\n",
    "            print(task.done())\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "```\n",
    "输出：（`wait`默认是等待全部完成）\n",
    "```\n",
    "True\n",
    "True\n",
    "True\n",
    "True\n",
    "```\n",
    "\n",
    "**指定等待的参数**：\n",
    "```py\n",
    "import time\n",
    "import urllib.request\n",
    "import concurrent.futures\n",
    "\n",
    "def get_html(url):\n",
    "    with urllib.request.urlopen(url) as conn:\n",
    "        return conn.read()\n",
    "\n",
    "def main():\n",
    "    url_list = [\n",
    "        \"https://www.baidu.com\", \"https://www.qq.com\", \"https://www.sogou.com\",\n",
    "        \"https://www.cnblogs.com\"\n",
    "    ]\n",
    "\n",
    "    with concurrent.futures.ThreadPoolExecutor() as executor:\n",
    "        tasks = {executor.submit(get_html, url): url for url in url_list}\n",
    "\n",
    "        # FIRST_COMPLETED：等待第一个完成就返回\n",
    "        done_set, no_done_set = concurrent.futures.wait(\n",
    "            tasks, return_when=concurrent.futures.FIRST_COMPLETED)\n",
    "\n",
    "        # 返回值是 `done=true的set集合` 和 `done=false的set` 组成的元组\n",
    "        print(done_set)  # 可以根据对应的set，进行相应处理\n",
    "        print(no_done_set)  # 可以根据对应的set，进行相应处理\n",
    "\n",
    "        # 我们来看看状态\n",
    "        for task in tasks:\n",
    "            print(task.done())\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "```\n",
    "输出：（返回值是 `done=true的set集合` 和 `done=false的set` 组成的元组）\n",
    "```\n",
    "{<Future at 0x24c30609b00 state=finished returned bytes>}\n",
    "{<Future at 0x24c30137c18 state=running>, <Future at 0x24c306090f0 state=running>, <Future at 0x24c30609ef0 state=running>}\n",
    "False\n",
    "False\n",
    "True\n",
    "False\n",
    "```\n",
    "#### `exception` and `add_done_callback`\n",
    "\n",
    "来个案例：\n",
    "```py\n",
    "import concurrent.futures\n",
    "\n",
    "def test1(name):\n",
    "    print(name)\n",
    "    return \"姓名：\" + name\n",
    "\n",
    "def test2(name):\n",
    "    raise Exception(\"我发送异常了！\")\n",
    "\n",
    "def call_back(future):\n",
    "    ex = future.exception()\n",
    "    if ex:\n",
    "        print(ex)\n",
    "    else:\n",
    "        print(future.result())\n",
    "\n",
    "def main():\n",
    "    with concurrent.futures.ThreadPoolExecutor() as executor:\n",
    "        future1 = executor.submit(test1, \"小明\")\n",
    "        future2 = executor.submit(test2, \"小张\")\n",
    "        future1.add_done_callback(call_back)\n",
    "        future2.add_done_callback(call_back)\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()\n",
    "```\n",
    "输出：\n",
    "```\n",
    "小明\n",
    "姓名：小明\n",
    "我发送异常了！\n",
    "```\n",
    "有这几种常见的异常：\n",
    "1. `concurrent.futures.CancelledError`\n",
    "2. `concurrent.futures.TimeoutError`\n",
    "3. `concurrent.futures.process.BrokenProcessPool`\n",
    "\n",
    "写在最后的话：线程现在虽然说了很多东西，其实等讲到了协程后，线程就基本上不太用了，基本上都是`进程+协程`\n",
    "\n",
    "用线程和进程的话基本上也是用最后说的通用方法，而什么时候用线程和进程这就看是否耗CPU（eg：`计算、图片处理这些进程处理可以充分发挥cpu性能`）\n",
    "\n",
    "---\n",
    "\n",
    "参考文档：\n",
    "```\n",
    "可以参考官方测试案例：\n",
    "https://github.com/lotapp/cpython3/blob/master/Lib/test/_test_multiprocessing.py\n",
    "\n",
    "线程之线程同步（C系）\n",
    "http://www.cnblogs.com/nufangrensheng/p/3521654.html\n",
    "\n",
    "Python多线程——线程同步机制（只是列举方法）\n",
    "http://www.cnblogs.com/Security-Darren/p/4732914.html\n",
    "\n",
    "Queue模块及源码分析\n",
    "http://blog.51cto.com/11026142/1867877\n",
    "http://blog.51cto.com/11026142/1879245\n",
    "\n",
    "Python多进程通信Queue、Pipe、Value、Array实例\n",
    "https://www.jb51.net/article/57666.htm\n",
    "\n",
    "理解Python并发编程一篇就够了 | 进程篇+线程篇\n",
    "https://blog.csdn.net/crisschan/article/details/53838622\n",
    "https://blog.csdn.net/crisschan/article/details/53838420\n",
    "\n",
    "Cpython解释器下实现并发编程——多进程、多线程、协程、IO模型\n",
    "https://www.cnblogs.com/happy-king/p/7844524.html\n",
    "\n",
    "Python的GIL是什么鬼，多线程性能究竟如何\n",
    "http://cenalulu.github.io/python/gil-in-python\n",
    "\n",
    "Actor模型概念\n",
    "http://www.sohu.com/a/219410350_465221\n",
    "https://en.wikipedia.org/wiki/Actor_model\n",
    "https://www.cnblogs.com/zangao/p/4887911.html\n",
    "https://blog.csdn.net/zhaodedong/article/details/73441303\n",
    "\n",
    "理解Python的PoolExecutor\n",
    "https://blog.csdn.net/jw690114549/article/details/69396277\n",
    "\n",
    "Java并发编程：Callable、Future和FutureTask\n",
    "http://www.cnblogs.com/dolphin0520/p/3949310.html\n",
    "\n",
    "RocketMQ学习-消息发布和订阅\n",
    "https://www.jianshu.com/p/fe8c89a781a3\n",
    "\n",
    "如何利用Golang为Python编写so动态库\n",
    "https://www.jianshu.com/p/8f0e7c39faca\n",
    "\n",
    "Go实现Python模块\n",
    "https://mp.weixin.qq.com/s/r-IoNkKW_ygGpLMQRhvdxg\n",
    "\n",
    "编写Python3的C扩展\n",
    "https://blog.csdn.net/baidu_35085676/article/details/79518777\n",
    "```"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
